3

Below code create new variable a_new/b_new/c_new , but have to input code in mutate one by one. Is there any convenient way ?

In actual, I have to create many variable ,for instance a_new/b_new/..../z_new. I don't want to input the variable calculating code one by one.

library(tidyverse)  

test_data <- data.frame(a=c(1:3),
                        b=c(3:5),
                        c=c(1:3),
                        a_increase=c(1:3)/100,
                        b_increase=c(3:5)/100,
                        c_increase=c(6:8)/100)

test_data %>% mutate(
  a_new =a* a_increase,
  b_new =b* b_increase,
  c_new =c* c_increase
)
benson23
  • 16,369
  • 9
  • 19
  • 38
anderwyang
  • 1,801
  • 4
  • 18

1 Answers1

4

Use across to specify your columns of interest, then get the corresponding columns that end with the string "_increase". Finally, use the .names argument to set new column names.

library(dplyr)

test_data %>% 
  mutate(across(a:c, ~get(paste0(cur_column(), "_increase")) * .x, .names = "{.col}_new"))

  a b c a_increase b_increase c_increase a_new b_new c_new
1 1 3 1       0.01       0.03       0.06  0.01  0.09  0.06
2 2 4 2       0.02       0.04       0.07  0.04  0.16  0.14
3 3 5 3       0.03       0.05       0.08  0.09  0.25  0.24
benson23
  • 16,369
  • 9
  • 19
  • 38
  • cur_column() means a:c ? Thanks1 – anderwyang Apr 14 '23 at 09:38
  • 1
    `cur_column` returns the column names specified in `across`. So in this case it returns "a", "b" and "c". That's why we can use `paste0` on `cur_column()` to get the "_increase" columns. – benson23 Apr 14 '23 at 09:47