在运行state_id时,我希望按species和mice::mice对数据进行分组,以计算值。我已经把它按state_id分组了,结果看起来比没有字节组好得多。
编辑...改进后的工作代码:
# 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)这也是可行的,但没有分组:
imp <- mice(data, m = 1, maxit = 3, method = 'norm.predict', seed = 500)
imp <- complete(imp, 1)所以,还有一个问题。
当我将变量state_id替换为species_id时,我遇到了一个错误:
lm.fit(x = x,y= y):0(非NA)情况下的错误
问题似乎是,一些物种的lat和长数据的值为零或没有。我通过删除所有没有lat和长数据的物种来证实了这一点,并且物种的估算是成功的。
group <- list("decimalLatitude" = "species_id",
"decimalLongitude" = "species_id")发布于 2021-06-08 20:24:08
您不应该直接使用mice.impute.bygroup。它是一个在指定method["x"] <- "bygroup"时被调用的函数,就像用"norm.predict"调用mice.impute.norm.predict一样(参见?mice.impute.norm.predict)。
下面是一些关于如何使用bygroup的示例代码。
样本数据
data <- iris
str(data)
# 'data.frame': 150 obs. of 5 variables:
# $ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
# $ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
# $ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
# $ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
# $ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
data[, -5] <- mice::ampute(data[, -5])$amp
init <- mice::mice(data, maxit = 0)按组(种)估算一个变量(Petal.Width)
meth <- init$meth
pred <- init$pred
imputationFunction <- list("Petal.Width" = meth["Petal.Width"])
meth["Petal.Width"] <- "bygroup"
group <- list("Petal.Width" = "Species")
pred[, "Species"] <- 0
imp <- mice::mice(data, meth = meth, pred = pred, m = 1,
group = group, imputationFunction = imputationFunction)所有变量的
meth <- init$meth
pred <- init$pred
imputationFunction <- as.list(meth[meth != ""])
meth[meth != ""] <- "bygroup"
group <- imputationFunction
group[] <- "Species"
pred[, "Species"] <- 0
imp <- mice::mice(data, meth = meth, pred = pred, m = 1,
group = group, imputationFunction = imputationFunction)进一步考虑
bygroup方法不允许对多个变量进行分组。您可以创建一个简单覆盖所有这些组的新变量。在内部,bygroup所做的就是将数据分成不同的组,所以这不是一个问题。
然而,在某种程度上,你必须考虑这是否是一种正确的做事方式。考虑多级归责可能更有价值。
https://stackoverflow.com/questions/67888945
复制相似问题