Search code examples
rdplyrmutate

Mutate specific colums and add pattern to the name


I would like to use mutate to add new columns to a data.frame based on specific colums divided by another column and keep the originalname plus a fixed pattern.

mtcars$mpg_HorsePower = mtcars$mpg / mtcars$hp
mtcars$cyl_HorsePower = mtcars$cyl / mtcars$hp
mtcars$disp_HorsePower = mtcars$disp / mtcars$hp
head(mtcars)
#                    mpg cyl disp  hp drat    wt  qsec vs am gear carb mpg_HorsePower cyl_HorsePower disp_HorsePower
# Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4      0.1909091     0.05454545        1.454545
# Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4      0.1909091     0.05454545        1.454545
# Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1      0.2451613     0.04301075        1.161290
# Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1      0.1945455     0.05454545        2.345455
# Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2      0.1068571     0.04571429        2.057143
# Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1      0.1723810     0.05714286        2.142857

I was hoping that something like this

mtcars %>% 
  mutate_at(vars(mpg:disp), funs(. / hp))

would work but does nothing.


Solution

  • Using dplyr::across you could achieve your desired result like so:

    library(dplyr, w = FALSE)
    
    mtcars2 <- mtcars %>% 
      mutate(across(mpg:disp, list(Horsepower = ~. / hp)))
    
    head(mtcars2)
    #>                    mpg cyl disp  hp drat    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
    #>                   mpg_Horsepower cyl_Horsepower disp_Horsepower
    #> Mazda RX4              0.1909091     0.05454545        1.454545
    #> Mazda RX4 Wag          0.1909091     0.05454545        1.454545
    #> Datsun 710             0.2451613     0.04301075        1.161290
    #> Hornet 4 Drive         0.1945455     0.05454545        2.345455
    #> Hornet Sportabout      0.1068571     0.04571429        2.057143
    #> Valiant                0.1723810     0.05714286        2.142857