R bygroup mice imputation (mice.impute.bygroup) doesnt work

I try do the Multiple Imputation with MICE in R, but I want to do it seperately for men and women (by “sex”).
I would like to use the bygroup function of the miceadds package, but unfortunately I always get a warning when trying to do multiple imputation.
If I take the “meth = meth.B2A.T1” argument out of the mice function, it works (but not separated by gender and with none of my formulae).

This is the code I used:

imp.B2A.T1 <- mice(data = B2A.T1, m = 20, maxit = 10, seed = 12345, print = FALSE)

meth.B2A.T1 <- imp.B2A.T1$meth
pred.B2A.T1 <- imp.B2A.T1$predictorMatrix

meth.B2A.T1["FAI_dif_proJahr"] <- "~I(FAI_dif/AgeDiff_T0_T1)" # use this formula to calculate the variable
pred.B2A.T1[c("AgeDiff_T0_T1", "FAI_dif"), "FAI_dif_proJahr"] <- 0 # Veränderung der predictorMatrix, FAI_dif_proJahr will not be used as predictor of AgeDiff_T0_T1 and FAI_dif


meth.B2A.T1["FTSpmolL_dif_proJahr"] <- "~I(FTSpmolL_dif/AgeDiff_T0_T1)" # use this formula to calculate the variable
pred.B2A.T1[c("AgeDiff_T0_T1", "FTSpmolL_dif"), "FTSpmolL_dif_proJahr"] <- 0


meth.B2A.T1["TestosteronnmolL_dif_proJahr"] <- "~I(TestosteronnmolL_dif/AgeDiff_T0_T1)" # use this formula to calculate the variable
pred.B2A.T1[c("AgeDiff_T0_T1", "TestosteronnmolL_dif"), "TestosteronnmolL_dif_proJahr"] <- 0 


meth.B2A.T1["DSST_richtige_dif_proJahr"] <- "~I(DSST_richtige_dif/AgeDiff_T0_T1)" # use this formula to calculate the variable
pred.B2A.T1[c("AgeDiff_T0_T1", "DSST_richtige_dif"), "DSST_richtige_dif_proJahr"] <- 0 

####4 do imputation seperately for men and women

imputationFunction.B2A.T1 <- list(meth.B2A.T1[meth.B2A.T1 != ""])
meth.B2A.T1[meth.B2A.T1 != ""] <- "bygroup"
group.B2A.T1 <- imputationFunction.B2A.T1
group.B2A.T1[] <- "sex"

pred.B2A.T1[,"sex"] <- 0

####4 imputation

imp.B2A.T1 <- mice(data = B2A.T1, m = 20, maxit = 10, seed = 12345, print = FALSE,
                   meth = meth.B2A.T1, pred = pred.B2A.T1,
                   group = group.B2A.T1, imputationFunction = imputationFunction.B2A.T1)

I get the following warning:
Error in [.data.frame(state_data, , group_vname) :
nicht definierte Spalten gewählt

(I don’t know why this is in German, my normal R language is English.)
In English it would be:

Error in [.data.frame(state_data, , group_vname) :
undefined columns selected

Leave a Comment