【发布时间】:2023-01-13 05:02:48
【问题描述】:
我正在尝试在 R 中测试各种插补方法,我编写了一个函数,它接受一个数据框,插入一些随机 NA 值,插补缺失值,然后使用 MAE 将插补方法与原始数据进行比较。
我的函数如下所示:
pacman::p_load(tidyverse)
impute_diamonds_accuracy <- function(df, col, prop) {
require(tidyverse)
# Sample the indices of the rows to convert to NA
n <- nrow(df)
idx_na <- sample(1:n, prop*n)
# Convert the values at the sampled indices to NA
df[idx_na, col] <- NA
# Impute missing values using mice with pmm method
imputed_df <- mice::mice(df, method='pmm', m=1, maxit=10)
imputed_df <- complete(imputed_df)
# Calculate MAE between imputed and original values
mae <- mean(abs(imputed_df[idx_na, col] - df[idx_na, col]), na.rm = TRUE)
return(list(original_data = df,imputed_data = imputed_df, accuracy = mae))
}
impute_diamonds_accuracy(df = diamonds, col = 'cut', prop = 0.02)
该函数在屏幕上显示它正在执行插补,但在执行 MAE 计算时失败并出现以下错误:
Error in imputed_df[idx_na, col] - df[idx_na, col] :
non-numeric argument to binary operator
我如何将原始数据与估算版本进行比较以了解准确性?
【问题讨论】:
标签: r function tidyverse imputation