【问题标题】:Calculate the accuracy of an imputation function in R计算 R 中插补函数的准确性
【发布时间】: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


    【解决方案1】:

    diamonds 是一个小问题。

    > library(ggplot2)
    > data(diamonds)
    > is_tibble(diamonds)
    [1] TRUE
    

    所以我们可能需要使用[[将列提取为向量

     mae <- mean(abs(imputed_df[[col]][idx_na] - df[[col]][idx_na]), na.rm = TRUE)
    

    【讨论】:

      猜你喜欢
      • 2021-05-10
      • 1970-01-01
      • 1970-01-01
      • 2017-02-19
      • 1970-01-01
      • 2010-12-12
      • 2012-07-10
      • 2019-02-14
      • 1970-01-01
      相关资源
      最近更新 更多