Search code examples
dplyrtidyverse

In r/dplyr, how to add new variables by batch according existing variables


There is raw_data, how to add new variables as yellow area in attached image ?

library(tidyverse)
raw_data <- data.frame(
  Category=c("A","B","C","D","E","F","G"),
 Amount=c(19,14,19,11,2,11,13),
 Ad=c(0.73,0.78,0.37,0.32,0.62,0.76,0.25),
 ST=c(0.54,0.74,0.86,0.57,0.98,0.58,0.35),
 WT=c(0.3,0.2,0.94,0.9,0.75,0.39,0.23),
 MM=c(0.79,0.35,0.87,0.76,0.74,0.55,0.72))

Below code can return the calculation result correctly, but the current variable be replaced and the variables name isn't what I want. I know that we can add the new variables separately (step by step ),is there any convenient method for this ? Thanks!

raw_data %>% mutate(Amount=as.character(Amount)) %>% 
  mutate(across(where(is.numeric),  ~ . * as.numeric(Amount)))

enter image description here


Solution

  • I guess all you need is the names argument of the across function:

    raw_data %>% 
        mutate(Amount=as.character(Amount)) %>% 
        mutate(across(where(is.numeric),  ~ . * as.numeric(Amount), .names = "{col}_AMOUNT"))
    
      Category Amount   Ad   ST   WT   MM Ad_AMOUNT ST_AMOUNT WT_AMOUNT MM_AMOUNT
    1        A     19 0.73 0.54 0.30 0.79     13.87     10.26      5.70     15.01
    2        B     14 0.78 0.74 0.20 0.35     10.92     10.36      2.80      4.90
    3        C     19 0.37 0.86 0.94 0.87      7.03     16.34     17.86     16.53
    4        D     11 0.32 0.57 0.90 0.76      3.52      6.27      9.90      8.36
    5        E      2 0.62 0.98 0.75 0.74      1.24      1.96      1.50      1.48
    6        F     11 0.76 0.58 0.39 0.55      8.36      6.38      4.29      6.05
    7        G     13 0.25 0.35 0.23 0.72      3.25      4.55      2.99      9.36