0

I've been running linear mixed models using an old version of lme4. Now that I have updated lme4 I'm getting the following error:

Error en [[<-.data.frame(*tmp*, i, value = integer(0)) : replacement has 0 rows, data has 4211

I found in this website an answer that suggests to put all the grouping variables within the data frame specified by the data argument. I've done that but my code still doesn't work.

Here it is:

msdgtot=glmer(sdg.dens ~ ngbr.trees + (1 + ngbr.trees | factor(species)), data=d.sdg.ngb,family=poisson)

Error en [[<-.data.frame(*tmp*, i, value = integer(0)) : replacement has 0 rows, data has 4211

Any idea why is this happening? Many thanks! Natalia Norden

zero323
  • 322,348
  • 103
  • 959
  • 935
user2949067
  • 11
  • 1
  • 1
  • Welcome to SO Natalia. Please read [How to make a great R reproducible example?](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and modify the question accordingly. – zero323 Nov 03 '13 at 03:01
  • 1
    can you convert `d.sdg.ngb$species` to a factor (if it isn't already) and try `glmer(sdg.dens ~ ngbr.trees + (1 + ngbr.trees | species)` ? results of `sessionInfo()` would be useful too ... the bug referred to previously ( http://stackoverflow.com/questions/19431863/lme4-upgrade-produces-error-message-error-in-data-frametmp-i-value/ ) should be fixed in version 1.0-5 ... – Ben Bolker Nov 03 '13 at 03:54

1 Answers1

7

This is indeed an as-yet-unfixed bug in lme4: https://github.com/lme4/lme4/issues/156 . However, the workaround is easy: just do conversions such as as.factor() and as.numeric() within the data frame, rather than within the formula, e.g.

d.sdg.ngb = transform(d.sdg.ngb,species=factor(species))
msdgtot = glmer(sdg.dens ~ ngbr.trees + (1 + ngbr.trees | species),
    data=d.sdg.ngb,family=poisson)

in general, I think this should not even be necessary -- at least recent versions of glmer automatically convert grouping variables such as species to factors -- but I can appreciate wanting to be careful/explicit. If for some reason I don't want to permanently convert the grouping variable to a factor, I usually make a factor version of the variable, e.g.

d.sdg.ngb = transform(d.sdg.ngb,fspecies=factor(species))

and then use fspecies rather than species in the formula.

For what it's worth, this would have been a problem in previously released versions of lme4 as well: with lme4.0 (the backward-compatible version),

gm1 <- glmer(cbind(incidence, size - incidence) ~ period + (1 | herd),
  data=cbpp,family=binomial)

works fine but

gm1 <- glmer(cbind(incidence, size - incidence) ~ period + (1 | factor(herd)),
data=cbpp,family=binomial)

gives Error in factor(herd) : object 'herd' not found (admittedly a less cryptic error message, but still an error).

Roland
  • 127,288
  • 10
  • 191
  • 288
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453