kosukeimai / mediation

R package mediation
58 stars 29 forks source link

Missing value where TRUE/FALSE needed & workaround #6

Closed aolney closed 6 years ago

aolney commented 6 years ago

Running the following model, with MapChange as a binary factor

medModel <- 
  lme4::glmer( MapChange ~ TallCondition + ( 1 | V1.ResponseID ), data=bin.tallSonaK, family=binomial(link="logit") )
outModel <- 
  lme4::lmer( SGAIN ~ MapChange + TallCondition + ( 1 | V1.ResponseID ), data=bin.tallSonaK )
med <-
  mediation::mediate(model.m=medModel, model.y=outModel,treat='TallCondition',mediator='MapChange',data=bin.tallSonaK)
summary(med)

yields the error message Error in if (xhat == 0) out <- 1 else { : missing value where TRUE/FALSE needed

I believe this is an error in function pval:

pval <- function(x, xhat){
  ## Compute p-values
  if (xhat == 0) out <- 1
  else {
    out <- 2 * min(sum(x > 0), sum(x < 0)) / length(x)
  }
  return(min(out, 1))
}

caused by xhat having value NA.

Interestingly I can remove this error by keeping MapChange as num instead of factor

aolney commented 6 years ago

If the problem is that factors are not allowed because of the interpretability of removing the intercept then this could be a simple documentation fix.

aolney commented 6 years ago

Ok, I stand corrected, this is in the documentation.

For binary response models, the ’mediator’ must be a numeric variable with values 0 or 1 as opposed to a factor.

I humbly suggest it also be included in the vignette as it is quite surprising, and the vignette includes binomial mediation examples

ghowoo commented 4 years ago

Thanks for the comment. I spent more than two hours trying to solve the problem before I found this. I would like to say this comment worths at least four hours.