2012-10-29 37 views
3

我是R編程語言的新手。我只是想知道是否有任何方法可以在我們的數據集中將的空值置於僅一列。因爲我所看到的所有插補命令和庫都會對整個數據集的空值進行插值。R中的插補

+6

這是一個非常寬泛的問題。請給出一些示例數據以及您已經嘗試過的內容(例如*您考慮過的所有impuation命令和軟件包)。 – mnel

回答

13

下面是使用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的詳細信息,歸集是如何實現的

+0

對不起,但您是否知道任何其他歸併不會影響均值和隨機值? –

+1

如果你更新你的問題,以反映你想要什麼,你已經嘗試...... – mnel

+3

另外*如果*你已經閱讀了'impute'的幫助文件(如我建議的!),你會看到你可以傳遞一個函數來進行插補。 – mnel

0

有很多的包,可以爲你做這樣的一個例子。 (有關數據的更多信息可能有助於提示您提供最佳選擇)

一個示例可以使用VIM包。

它有一個叫做的kNN(K近鄰歸集) 這個函數有一個選項變量在那裏你可以指定哪些變量應歸咎於功能。

下面是一個例子:

library("VIM") 
kNN(sleep, variable = c("NonD","Gest")) 

我在這個例子中使用的數據集的睡眠自帶VIM一起。

如果您想要使用時間序列插補軟件包進行插值的列中存在一些時間依賴性,那麼也可以使用該插件。

0

爲什麼不使用更復雜的插補算法,如鼠標(鏈式方程的多重插補)?下面是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