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

如何用dplyr对数字列名的DataFrame执行mutate或重命名列?

问题描述

我用pivot_wider生成了一个DataFrame,其中两列的列名是数字(2012、2013)。尝试用dplyr的mutate计算这两列的差值时失败,推测是列名为数字导致的问题。想知道可行的mutate实现方法,或者用dplyr重命名这些列的方案。

数据示例:

df <- structure(list(Age_Band = c("20-30", "20-30", "30-40", "30-40", 
                                  "40-50", "40-50", "50-60", "50-60"), Gender = c("female", "male", 
                                                                                  "female", "male", "female", "male", "female", "male"), `2012` = c(20881.9, 
                                                                                                                                                    19962.1, 29710.85, 26187.4, 50536.05, 21359.3, 26447.65, 24520.95
                                                                                  ), `2013` = c(20132.4, 17268.15, 22622.1, 21543.05, 39569.15, 
                                                                                                15701.1, 21450.95, 21020.6)), class = c("tbl_df", "tbl", "data.frame"
                                                                                                ), row.names = c(NA, -8L))

尝试的代码(执行失败):

df %>%
  mutate(difference = 2013 - 2012)
解决方法

方法一:直接在mutate中引用数字列名

R会把纯数字的列名默认识别为数值,而非列对象,所以需要用反引号(`)将列名包裹,强制R识别为列名:

df %>%
  mutate(difference = `2013` - `2012`)

方法二:重命名数字列

如果不想每次引用都加反引号,可以用dplyr的重命名工具修改列名:

单个重命名

# 先重命名列
df_renamed <- df %>%
  rename(year_2012 = `2012`, year_2013 = `2013`)

# 再计算差值
df_renamed %>%
  mutate(difference = year_2013 - year_2012)

批量重命名(适合多数字列场景)

用rename_with匹配所有4位数字的列,统一添加前缀:

df_renamed <- df %>%
  rename_with(~ paste0("year_", .), matches("^\\d{4}$"))

df_renamed %>%
  mutate(difference = year_2013 - year_2012)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 09:00:05