在R中如何向一系列变量添加后缀?

huangapple go评论61阅读模式
英文:

How to add a suffix to a sequence of variables in R?

问题

你可以尝试这样修改代码来避免错误:

data <- data %>%
  rename_at(vars(AGRA_A00_A09:AGRII_U80_U89), ~paste0(., "_cor"))

这应该能解决你遇到的错误。

英文:

My dataset has over 6k variables and I need to add a suffix to a sequence of variables, but not all of them. I'm trying:

data &lt;- data %&gt;%
  rename_at(AGRA_A00_A09:AGRII_U80_U89, ~paste0(., &quot;_cor&quot;))

But I get the following error:

Error: object &#39;AGRA_A00_A09&#39; not found

I've tried putting quote marks on the variables names and using across, but it still doesn't work. What am I doing wrong?

答案1

得分: 2

Close, use rename_with:

mtcars %>%
  rename_with(disp:drat, .fn = ~ paste0(., "_cor")) %>%
  head()
#                    mpg cyl disp_cor hp_cor drat_cor    wt  qsec vs am gear carb
# Mazda RX4         21.0   6      160    110     3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag     21.0   6      160    110     3.90 2.875 17.02  0  1    4    4
# Datsun 710        22.8   4      108     93     3.85 2.320 18.61  1  1    4    1
# Hornet 4 Drive    21.4   6      258    110     3.08 3.215 19.44  1  0    3    1
# Hornet Sportabout 18.7   8      360    175     3.15 3.440 17.02  0  0    3    2
# Valiant           18.1   6      225    105     2.76 3.460 20.22  1  0    3    1
英文:

Close, use rename_with:

mtcars %&gt;%
  rename_with(disp:drat, .fn = ~ paste0(., &quot;_cor&quot;)) %&gt;%
  head()
#                    mpg cyl disp_cor hp_cor drat_cor    wt  qsec vs am gear carb
# Mazda RX4         21.0   6      160    110     3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag     21.0   6      160    110     3.90 2.875 17.02  0  1    4    4
# Datsun 710        22.8   4      108     93     3.85 2.320 18.61  1  1    4    1
# Hornet 4 Drive    21.4   6      258    110     3.08 3.215 19.44  1  0    3    1
# Hornet Sportabout 18.7   8      360    175     3.15 3.440 17.02  0  0    3    2
# Valiant           18.1   6      225    105     2.76 3.460 20.22  1  0    3    1

huangapple
  • 本文由 发表于 2023年5月7日 08:41:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76191781.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定