Factor/level error in mixed model

217 views Asked by At

I am running a mixed model on something akin to this data:

df<-data.frame(stage=c("a","a","a","a","b","b","b","b","c","c","c","c"),
nematode=c("fn","fn","bn","bn","fn","fn","bn","bn","fn","fn","bn","bn"),
id2=c(1,2,3,4,1,2,3,4,1,2,3,4),
value=c(1,0,0,2,3,1,1,2,0,0,0,2))

The model I am trying to fit is:

stage.id <- function(x) round(summary(glmer(value ~ stage + (1 | id2),family="poisson", data = x))$coefficients[2, c(1, 2, 4)], 3)
models.id0  <- ddply(tree2, .(stage, nematode), stage.id)

However, when I run this, I continually get an error:

Error in contrasts<-(*tmp*, value = contr.funs[1 + isOF[nn]]) : contrasts can be applied only to factors with 2 or more levels

which doesn't make sense to me given that I've used the nlevels() command on each of the factors (df$stage and df$nematode) and they are 3 and 2, respectively. Any sense what might be awry?

1

There are 1 answers

5
Ben Bolker On

You have stage as a fixed effect in your model, but you're trying to fit the model for every combination of stage and nematode (ddply(tree2, .(stage, nematode), ...)). Thus in each chunk of the data there's only a single stage value, which causes the error.

You could:

  • apply only over nematode values, i.e. ddply(tree2,.(nematode), ...)
  • leave stage out of your model, i.e. fit the model value ~ 1 + (1 | id2)

According to your comment ("my goal is to compare the stages for each of the types of nematodes. I.e., for each type of nematode (e.g., bn) do the stages differ"), you want the former solution (apply only over nematode values).