You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R函数减少不同数据集的重复代码及绘图代码?

用自定义R函数简化重复的plot_missing调用

当然可以通过自定义包装函数消除这类重复代码。核心思路是把所有固定不变的参数封装到自定义函数里,仅将需要变化的数据集作为输入参数传入。

步骤1:定义自定义包装函数

# 自定义函数,封装固定参数,仅接收数据集作为必传参数
plot_custom_missing <- function(data, title = "Missing User Data") {
  plot_missing(
    data,
    group = c("Excellent" = 0.01, "Good" = 0.3, "Ok" = 0.6, "Bad" = 0.9),
    missing_only = TRUE,
    title = title,
    ggtheme = theme_minimal(),
    theme_config = list(legend.position = c("bottom"))
  )
}

这里给title设置了默认值,后续如果需要给不同数据集单独设置标题,直接传参覆盖即可,无需修改函数核心逻辑。

步骤2:调用简化后的函数

现在只需一行代码就能完成单个数据集的缺失值可视化:

plot_custom_missing(prospects6K)
plot_custom_missing(testing5K)
plot_custom_missing(training15K)

# 如需给特定数据集修改标题,直接传参:
plot_custom_missing(training15K, title = "Training Dataset Missing Values")

进阶:批量处理多个数据集

如果你的数据集都存储在一个列表中,还可以用purrr::map批量生成所有可视化结果:

# 将数据集存入列表
data_list <- list(prospects6K, testing5K, training15K)
# 批量调用自定义函数
purrr::map(data_list, plot_custom_missing)

内容的提问来源于stack exchange,提问作者wahlaoeh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 07:05:31