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

如何在R中为含Medication的列批量创建编码新列

批量生成Medication列的编码列

编码规则

  • paracetamol、ibuprofen → 编码为1
  • opiate、ketamine → 编码为2
  • 其余所有值 → 编码为3

方法1:使用dplyr批量处理(推荐)

利用tidyverse语法简洁高效完成多列批量操作:

# 首次使用先安装dplyr包
# install.packages("dplyr")
library(dplyr)

# 原始数据集
df <- data.frame(id = paste0("ID",1:4),
                 Medication1= c("paracetamol", "ibuprofen", "opiate", "sertraline"),
                 Medication2= c("Lipitor", "ketamine", "zoloft", "xanax"),
                 Medication3= c("ibuprofen", "paracetamol", "Zocor", "Zestril"),
                 other= LETTERS[1:4])

# 批量生成编码列
df <- df %>%
  mutate(
    across(
      starts_with("Medication"),  # 匹配所有以Medication开头的列
      ~case_when(
        .x %in% c("paracetamol", "ibuprofen") ~ 1,
        .x %in% c("opiate", "ketamine") ~ 2,
        TRUE ~ 3
      ),
      .names = "{.col}_coded"  # 新列命名规则:原列名+_coded
    )
  )

方法2:基础R循环实现

若偏好基础R语法,可通过循环处理目标列:

# 原始数据集
df <- data.frame(id = paste0("ID",1:4),
                 Medication1= c("paracetamol", "ibuprofen", "opiate", "sertraline"),
                 Medication2= c("Lipitor", "ketamine", "zoloft", "xanax"),
                 Medication3= c("ibuprofen", "paracetamol", "Zocor", "Zestril"),
                 other= LETTERS[1:4])

# 筛选所有含"Medication"的列名
med_cols <- grep("Medication", names(df), value = TRUE)

# 循环处理每一列
for(col in med_cols) {
  df[[paste0(col, "_coded")]] <- ifelse(
    df[[col]] %in% c("paracetamol", "ibuprofen"),
    1,
    ifelse(
      df[[col]] %in% c("opiate", "ketamine"),
      2,
      3
    )
  )
}

验证结果

执行代码后查看更新后的数据集:

print(df)

会看到新增Medication1_coded、Medication2_coded、Medication3_coded三列,编码结果符合要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 05:12:10