【问题标题】:R - Getting Imputed Missing Values back into dataframeR - 将估算的缺失值返回到数据框中
【发布时间】:2017-06-20 05:54:22
【问题描述】:

我正在使用 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]
...

这行得通。但是必须有一种更有效的方法来完成此操作,而无需对所有列进行复制/粘贴。

有什么想法吗?

【问题讨论】:

    标签: r imputation hmisc


    【解决方案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]
    

    【讨论】:

    • 谢谢!它工作得很好。事实上,我可能跳过了那个功能。
    • 有什么方法可以用多个插补的平均值而不是任何特定数字 (imputation=1) 替换值?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多