Search code examples
rdplyrtidyversemutate

How to create new columns more conveniently with partially matched names?


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
)

Solution

  • 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