簡體   English   中英

R - 將估算的缺失值返回到數據框中

[英]R - Getting Imputed Missing Values back into dataframe

我正在使用aregImpute估算R 數據幀 (bn_df) 上的缺失值。

代碼是這樣的:

library(Hmisc)
impute_arg <- aregImpute(~ TI_Perc + AS_Perc + 
                         CD_Perc + CA_Perc + FP_Perc, 
                         data = bn_df, n.impute = 5)

它工作正常。

問題出在后面。 將值放回原始數據框中。

我可以做到,只是方式不太優雅。 我基本上必須為所有列復制/粘貼以下行:

bn_df$CD_Perc[impute_arg$na$CD_Perc] <- impute_arg$imputed$CD_Perc[,1]
bn_df$FP_Perc[impute_arg$na$FP_Perc] <- impute_arg$imputed$FP_Perc[,1]
...

這有效。 但是必須有一種更有效的方法來完成此操作,而無需對所有列進行復制/粘貼。

有任何想法嗎?

您可以使用函數impute.transcan 由於您尚未提供數據,因此我從aregImpute的文檔中復制了一個示例。

# The data
x1 <- factor(sample(c('a','b','c'),1000,TRUE))
x2 <- (x1=='b') + 3*(x1=='c') + rnorm(1000,0,2)
x3 <- rnorm(1000)
y  <- x2 + 1*(x1=='c') + .2*x3 + rnorm(1000,0,2)
orig.x1 <- x1[1:250]
orig.x2 <- x2[251:350]

# Insert NAs
x1[1:250] <- NA
x2[251:350] <- NA

# Create a data frame 
d <- data.frame(x1,x2,x3,y)
# Find value of nk that yields best validating imputation models
# tlinear=FALSE means to not force the target variable to be linear

# Use imputation 
f <- aregImpute(~y + x1 + x2 + x3, nk=c(0,3:5), tlinear=FALSE,
                data=d, B=10) # normally B=75

# Get the imputed values
imputed <-impute.transcan(f, data=d, imputation=1, list.out=TRUE, pr=FALSE, check=FALSE)

# convert the list to the database
imputed.data <- as.data.frame(do.call(cbind,imputed))

# arrange the columns accordingly
imputed.data <- imputed.data[, colnames(d), drop = FALSE]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM