【发布时间】:2012-10-18 08:45:49
【问题描述】:
我是 R 编程语言的新手。我只是想知道有没有办法在我们的数据集中估算 只有一列 的空值。因为我见过的所有插补命令和库,都是插补整个数据集的空值。
【问题讨论】:
-
这是一个非常广泛的问题。请给出一些示例数据以及您尝试过的内容(例如您考虑过的所有估算命令和包)。
标签: r imputation
我是 R 编程语言的新手。我只是想知道有没有办法在我们的数据集中估算 只有一列 的空值。因为我见过的所有插补命令和库,都是插补整个数据集的空值。
【问题讨论】:
标签: r imputation
这是使用Hmisc 包和impute 的示例
library(Hmisc)
DF <- data.frame(age = c(10, 20, NA, 40), sex = c('male','female'))
# impute with mean value
DF$imputed_age <- with(DF, impute(age, mean))
# impute with random value
DF$imputed_age2 <- with(DF, impute(age, 'random'))
# impute with the media
with(DF, impute(age, median))
# impute with the minimum
with(DF, impute(age, min))
# impute with the maximum
with(DF, impute(age, max))
# and if you are sufficiently foolish
# impute with number 7
with(DF, impute(age, 7))
# impute with letter 'a'
with(DF, impute(age, 'a'))
查看?impute 了解有关如何实施插补的详细信息
【讨论】:
impute 的帮助文件(正如我所建议的!),您会看到您可以传递一个函数来进行插补。跨度>
有很多软件包可以为您做到这一点。 (有关数据的更多信息可能有助于向您推荐最佳选择)
一个例子是使用 VIM 包。
它有一个叫做kNN的函数(k-nearest-neighbor imputation) 此函数有一个选项variable,您可以在其中指定应估算哪些变量。
这是一个例子:
library("VIM")
kNN(sleep, variable = c("NonD","Gest"))
我在这个例子中使用的睡眠数据集是随 VIM 一起提供的。
如果您希望使用时间序列插补包来插补您的列中存在一些时间依赖性,这也是有意义的。在这种情况下,您可以使用例如 imputeTS 包。 这是一个例子:
library(imputeTS)
na_kalman(tsAirgap)
此处用作示例的 tsAirgap 数据集也与 imputeTS 一起提供。
【讨论】:
为什么不使用更复杂的插补算法,例如小鼠(链式方程的多重插补)?下面是 R 中的代码 sn-p,您可以根据自己的情况进行调整。
library(mice)
#get the nhanes dataset
dat <- mice::nhanes
#impute it with mice
imp <- mice(mice::nhanes, m = 3, print=F)
imputed_dataset_1<-complete(imp,1)
head(imputed_dataset_1)
# age bmi hyp chl
# 1 1 22.5 1 118
# 2 2 22.7 1 187
# 3 1 30.1 1 187
# 4 3 24.9 1 186
# 5 1 20.4 1 113
# 6 3 20.4 1 184
#Now, let's see what methods have been used to impute each column
meth<-imp$method
# age bmi hyp chl
#"" "pmm" "pmm" "pmm"
#The age column is complete, so, it won't be imputed
# Columns bmi, hyp and chl are going to be imputed with pmm (predictive mean matching)
#Let's say that we want to impute only the "hyp" column
#So, we set the methods for the bmi and chl column to ""
meth[c(2,4)]<-""
#age bmi hyp chl
#"" "" "pmm" ""
#Let's run the mice imputation again, this time setting the methods parameter to our modified method
imp <- mice(mice::nhanes, m = 3, print=F, method = meth)
partly_imputed_dataset_1 <- complete(imp, 3)
head(partly_imputed_dataset_1)
# age bmi hyp chl
# 1 1 NA 1 NA
# 2 2 22.7 1 187
# 3 1 NA 1 187
# 4 3 NA 2 NA
# 5 1 20.4 1 113
# 6 3 NA 2 184
【讨论】: