估算 N.A。 R 中的二进制数据

IMPUTE N.A. BINARY SEX DATA in R

我有一个带有二进制变量“sex”的数据框“df_customers”。在这一列中,有 1.5% 缺失,它们是 NA。 非缺失值中,“男性”占60.81%,其余显然为“女性”。

我已将这些比例分配为值 males_impute 和 females_impute:

# PROPORTION OF NAs IN VARIABLE SEX

customer_NAs <- nrow(filter(df_customers, is.na(sex)))

# IMPUTATION PROPORTIONS OF MALE / FEMALE ACC. TO COMPLETE VALUES

males_impute <- (nrow(filter(df_customers, sex=="Male")) / 
   ((nrow(df_customers)) - customer_nas) * 100)

females_impute <- (nrow (filter (df_customers, sex=="Female")) / 
   ((nrow(df_customers)) - customer_NAs) * 100)


R 中是否有一种针对“男性”和“女性”的插补方法可以随机但根据这些比例将值插补到 NA 中?谢谢!

当然--dplyr::coalesce 对填充 NA 很有用,并且由于您的插补是纯随机的,我们可以使用 runif() 生成随机数并赋值:

df_customers %>%
  mutate(
    sex = coalesce(sex, ifelse(runif(n()) < females_impute / 100, "Female", "Male"))
  )

作为旁注,您可以看到您的代码通过包含 * 100 将比例转换为百分比。这个答案然后需要转换回 / 100 的比例。一般来说,我建议在代码中将其保留为比例,因为使用原始比例进行计算效果更好。如果要显示或报告百分比,请使用 scales::percent() 对其进行转换、舍入和格式化。 (scales 是一个 ggplot2 依赖项,因此您可能已经安装了它。)