MichaelChirico / r-bugs

A ⚠️read-only⚠️mirror of https://bugs.r-project.org/
20 stars 0 forks source link

[BUGZILLA #17192] nlme Variogram.lme fails for data with 1-observation groups #6367

Closed MichaelChirico closed 4 years ago

MichaelChirico commented 4 years ago

The following code fails in nlme > 3.1-122:

library("nlme")
## subset BodyWeight data such that it contains a 1-observation group
BW <- subset(BodyWeight, !(Rat=="1" & Time > 1))
fm2 <- lme(fixed = weight&sim; Time * Diet, random =&sim; 1 | Rat, data = BW)
Variogram(fm2, form =&sim; Time | Rat)

The error from the last call is

Error in res[[i]] : subscript out of bounds

with traceback()

5: Variogram(res[[i]], distance[[i]])
4: FUN(X[[i]], ...)
3: lapply(seq_along(levGrps), function(i) Variogram(res[[i]], distance[[i]]))
2: Variogram.lme(fm2, form =&sim;Time | Rat)
1: Variogram(fm2, form =&sim;Time | Rat)

Digging into Variogram.lme(), the problem is within lines 2714-2719 of the lme.R source file:

res <- split(res, grps)
res <- res[lengths(res) > 1] # no 1-observation groups
levGrps <- levels(grps)
val <- lapply(seq_along(levGrps),
              function(i) Variogram(res[[i]], distance[[i]]))
names(val) <- levGrps

Initially, 'res' is of the same length as levels(grps), but groups with only one observation are subsequently dropped, which eventually causes res[[i]] to be out of bounds.

To fix this, one could, e.g., use val <- mapply(Variogram, res, distance, SIMPLIFY = FALSE, USE.NAMES = FALSE) or replace 'seq_along(levGrps)' by 'seq_along(res)'. In either case, the last line 'names(val) <- levGrps' has to be replaced by 'names(val) <- names(res)' as well.

PS: In the context of this bug, it is worth mentioning that there is another bug related to data containing 1-observation groups, see https://bugs.r-project.org/bugzilla/show_bug.cgi?id=16806


METADATA

MichaelChirico commented 4 years ago

(In reply to Sebastian Meyer from comment #0)

Thank you Sebastian, for the reproducible example.

Indeed (as you alluded to), this is a relatively new bug which did not show in nlme 3.1-121.

Also with your analysis, I will fix this.


PS: In the context of this bug, it is worth mentioning that there is another
bug related to data containing 1-observation groups, see
https://bugs.r-project.org/bugzilla/show_bug.cgi?id=16806

Indeed. But that seems to be a long-standing problem (present also in 3.1-121 or 3.1-110).. still, we'd look at it, notably after such constructive analysis as this one!


METADATA

MichaelChirico commented 4 years ago

Fixed - very much along your suggestions - on R-forge, with subversion rev 7299. Thank you, Sebastian, once more.


METADATA