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

合并ICPC相关数值列时mutate函数报错的R语言技术问询

问题解决方法

报错原因

你在mutate中用双引号包裹列名,R会将其识别为字符串字面量,而非数据框中的列引用——本质是在尝试对两个字符串做加法,而非数值列,因此触发non numeric argument to binary operator错误。

单个列的正确写法

由于列名包含特殊符号|,必须用**反引号(`)**引用列名,代码如下:

df1 <- df %>%
  mutate(`R74|65_plus|J01CA04` = `R74|65_75|J01CA04` + `R74|75_plus|J01CA04`)

大型数据集批量处理方案

如果你的数据集有大量类似的年龄组合需要合并(比如多个ICPC_code、处方代码),推荐用长表转宽表的方式批量处理,效率更高:

library(dplyr)
library(tidyr)

df1 <- df %>%
  # 宽表转长表,拆分列名为三个维度
  pivot_longer(
    cols = starts_with("R"), # 假设所有目标列以R开头,可根据实际调整
    names_to = c("ICPC", "age_group", "prescription"),
    names_sep = "\\|",
    values_to = "patient_count"
  ) %>%
  # 合并目标年龄组
  mutate(age_group = case_when(
    age_group %in% c("65_75", "75_plus") ~ "65_plus",
    TRUE ~ age_group # 保留其他年龄组不变
  )) %>%
  # 按全科诊所、ICPC、年龄组、处方分组求和
  group_by(across(-patient_count)) %>%
  summarise(patient_count = sum(patient_count), .groups = "drop") %>%
  # 转回宽表格式
  pivot_wider(
    names_from = c("ICPC", "age_group", "prescription"),
    names_sep = "\\|",
    values_from = "patient_count"
  )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 10:42:43