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

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

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

问题

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

  1. data <- data %>%
  2. 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:

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

But I get the following error:

  1. 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:

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

Close, use rename_with:

  1. mtcars %&gt;%
  2. rename_with(disp:drat, .fn = ~ paste0(., &quot;_cor&quot;)) %&gt;%
  3. head()
  4. # mpg cyl disp_cor hp_cor drat_cor wt qsec vs am gear carb
  5. # Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
  6. # Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
  7. # Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
  8. # Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
  9. # Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
  10. # 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:

确定