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

如何批量将数据框多列中匹配规则的ATC编码替换为NA

批量替换ATC编码为NA的解决方案

问题分析

你之前的方法错误在于用apply按行调用replace_with_na,该函数不需要逐行处理,直接针对目标列操作即可,所以导致生成大量tibble,未达到预期效果。下面提供两种高效的批量处理方法:


方法一:tidyverse工具链(推荐)

适合习惯tidyverse语法的用户,代码简洁易读:

# 加载所需包
library(dplyr)
library(stringr)

# 将多个排除规则合并为单个正则表达式
exclude_pattern <- paste(exclude, collapse = "|")

# 批量处理所有ATC编码列
dset_clean <- dset %>%
  mutate(
    across(
      .cols = starts_with("ATC_code"), # 匹配所有以ATC_code开头的列
      .fns = ~ ifelse(str_detect(., exclude_pattern), NA, .) # 符合规则则替换为NA
    )
  )

如果习惯用naniar包的replace_with_na函数,也可以这样写:

library(naniar)

dset_clean <- dset %>%
  replace_with_na_at(
    .vars = vars(starts_with("ATC_code")),
    condition = ~ str_detect(., exclude_pattern)
  )

方法二:Base R实现

无需额外加载包,适合偏好原生R语法的用户:

# 筛选出所有ATC编码列的位置
atc_col_indices <- grep("^ATC_code", names(dset))
# 合并排除规则为单个正则表达式
exclude_pattern <- paste(exclude, collapse = "|")

# 批量替换符合规则的编码为NA
dset[, atc_col_indices] <- lapply(dset[, atc_col_indices], function(col) {
  col[grepl(exclude_pattern, col)] <- NA
  col
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 14:22:28