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

如何用dplyr的mutate_at为data.frame生成带固定后缀的计算列?

正确实现方法

推荐写法(dplyr 1.0.0+,官方推荐)

使用mutate()搭配across()函数,通过.names参数指定新列的命名规则,既能保留原列,又能生成带指定后缀的新列:

library(dplyr)

# 生成带_HorsePower后缀的新列,原列保留
mtcars_modified <- mtcars %>%
  mutate(across(c(mpg, cyl, disp), ~ .x / hp, .names = "{col}_HorsePower"))
  • across(c(mpg, cyl, disp)):指定要处理的目标列,也可以用vars(mpg:disp)选择连续列
  • ~ .x / hp:定义处理逻辑,.x代表当前遍历到的列
  • .names = "{col}_HorsePower":新列名模板,{col}会自动替换为原列名,最终生成mpg_HorsePower、cyl_HorsePower、disp_HorsePower

旧版写法(dplyr 1.0.0之前)

如果使用旧版dplyr,需要在mutate_at()的funs()里指定后缀命名,避免覆盖原列:

mtcars_modified <- mtcars %>%
  mutate_at(vars(mpg:disp), funs(HorsePower = . / hp))

这里funs(HorsePower = . / hp)会自动给原列名加上_HorsePower后缀,生成新列。

你之前的代码为什么"无效果"

你写的mtcars %>% mutate_at(vars(mpg:disp), funs(. / hp))会直接覆盖原有的mpg、cyl、disp列,而不是新增列,所以看起来没有生成你想要的新列(实际是替换了原列数据)。只有指定新列的命名规则,才能保留原列并生成新增列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:40:54