harrelfe/Hmisc

`fit.mult.impute(fit.reps=TRUE)` with MICE errors out (`invalid 'length' argument`)

krassowski opened this issue · 1 comments

In R 4.0 and R 4.1 calling fit.mult.impute results in:

Error in vector("list", n.impute) : invalid 'length' argument` if `n.impute

if n.impute is not explicitly specified. Here is a reproducer:

set.seed(1)
x1 <- factor(sample(c('a', 'b', 'c'), 100, TRUE))
x2 <- (x1=='b') + 3 * (x1=='c') + rnorm(100)
y  <- x2 + 1 * (x1=='c') + rnorm(100)
x1[1:20] <- NA
x2[18:23] <- NA
d <- data.frame(x1, x2, y)
f <- mice(d, print=FALSE)
# works
h <- fit.mult.impute(y ~ x1 + x2, lm, f, data=d)
# works
h <- fit.mult.impute(y ~ x1 + x2, lm, f, data=d, fit.reps=TRUE, n.impute=f$m)
# does not work
h <- fit.mult.impute(y ~ x1 + x2, lm, f, data=d, fit.reps=TRUE)

This is because when MICE is passed n.impute is only defined (line 17) after it is used (line 13):

fits <- if(fit.reps) vector('list', n.impute)
used.mice <- any(class(xtrans)=='mids')
if (used.mice && !requireNamespace("mice", quietly = TRUE))
stop("This data requires the 'mice' package.")
if(used.mice && missing(n.impute)) n.impute <- xtrans$m

The fix could be as simple as moving line 13 after line 17.

Thanks for this and for the fix which will be in Hmisc 4.7-1