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

R如何对前缀为Col_a_的批量列用众数替换缺失值

实现方法1:基础R版本(无需加载额外包)

你之前自定义的getmode函数可以保留,只需要先用正则匹配出所有符合命名规则的列,再用lapply批量处理即可:

# 保留原有的众数计算函数
getmode <- function(v) {
   uniqv <- unique(v)
   uniqv[which.max(tabulate(match(v, uniqv)))]
}

# 匹配所有以Col_a_开头的列名
target_cols <- grep("^Col_a_", names(df), value = TRUE)

# 批量替换对应列的NA为该列众数
df[target_cols] <- lapply(df[target_cols], function(x) {
  x[is.na(x)] <- getmode(x)
  return(x)
})

实现方法2:tidyverse风格(代码更简洁)

如果你习惯用dplyr的管道语法,可以用across函数批量处理匹配到的列:

library(dplyr)

getmode <- function(v) {
   uniqv <- unique(v)
   uniqv[which.max(tabulate(match(v, uniqv)))]
}

df <- df %>%
  mutate(across(starts_with("Col_a_"), ~replace(., is.na(.), getmode(.))))

两种方法都支持任意数量符合Col_a_前缀规则的列,不需要手动逐个指定列名,修改匹配规则也可以快速适配其他列名格式的需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:15:04