I would like to group my data by state_id and species when I run mice::mice to impute values. I've got it grouped by state_id and results are looking much better than without the bygroup.
mice.impute.bygroup: Groupwise Imputation Function
Edit... improved, working code:
# Modify df name and method
init <- mice::mice(data, method = "pmm", maxit = 0)
meth <- init$meth
pred <- init$pred
# Impute variables by group (state_id)
imputationFunction <- list("decimalLatitude" = meth["decimalLatitude"],
"decimalLongitude" = meth["decimalLongitude"])
meth[c("decimalLatitude", "decimalLongitude")] <- "bygroup"
group <- list("decimalLatitude" = "state_id",
"decimalLongitude" = "state_id")
# Remove variables as predictors but they can still be imputed.
pred[, c("coordinateUncertaintyInMeters", "geoprivacy_id")] <- 0
set.seed(500)
imp <- mice::mice(data, meth = meth, pred = pred, m = 1,
group = group, imputationFunction = imputationFunction)
imp <- complete(imp)
This works too, but no bygroup:
imp <- mice(data, m = 1, maxit = 3, method = 'norm.predict', seed = 500)
imp <- complete(imp, 1)
So, one question remains.
- Can I group by multiple variables?
When I replace the variable state_id with species_id, I'm running into an error:
Error in lm.fit(x = x, y = y) : 0 (non-NA) cases
The problem seems to be that some species have zero or no values for lat and long data. I confirmed this for one state by removing all species with no lat and long data and the imputation by species was successful.
group <- list("decimalLatitude" = "species_id",
"decimalLongitude" = "species_id")