在R中的填补缺失值问题

5

我是R编程语言的新手。我想知道是否有办法填充我们数据集中仅有一个列的空值。因为我看到的所有填充命令和库都会填充整个数据集中的空值。


6
这是一个非常广泛的问题,您需要提供一些示例数据以及您已经尝试过的内容(例如您考虑过的所有填补缺失值的命令和包)。请提供更具体的信息。 - mnel
3个回答

14

这里是使用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,以了解如何实现填补缺失值的具体细节。


抱歉,你知道有没有其他的填充方法,不是用平均值和随机值来填充的吗? - Mehrdad Rohani
1
如果您更新问题以反映您想要的和尝试过的内容...... - mnel
3
此外,如果你已经阅读了impute的帮助文件(就像我建议的那样!),你会发现可以传递一个函数来执行填充。 - mnel

2
为什么不使用更复杂的插补算法,例如mice(Multiple Imputation by Chained Equations)?以下是R中的代码片段,您可以根据自己的情况进行调整。
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

1
有许多可以为您完成此操作的软件包。 (提供更多关于数据的信息可以帮助建议最佳选项)
一个例子是使用VIM软件包。
它有一个名为kNN(k最近邻插补)的函数, 此函数具有一个variable选项,您可以在其中指定要插补的变量。
以下是一个示例:
library("VIM")
kNN(sleep, variable = c("NonD","Gest"))

我在这个例子中使用的睡眠数据集是随VIM一起提供的。
如果您要填充列中存在一些时间依赖关系,则使用时间序列插补包可能也是有意义的。在这种情况下,您可以使用例如imputeTS包。 以下是一个示例:
  library(imputeTS)
  na_kalman(tsAirgap)

这里使用的 tsAirgap 数据集是 imputeTS 中的一个示例数据集。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接