Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through a predefined list of variable and mutate many new columns in R?

Tags:

r

dplyr

My objective is to read the variables from a list and compute new variables as stated in the list. The original list contains hundreds of variables.

For illustration purposes, I will use the example below. Let's say I have a list of variables with 3 columns with example below.

alist <- tibble(
  numerator = c("mpg", "cyl", "disp"),
  denominator = c("wt", "drat", "wt"),
  newvar = c("mpg_wt", "cyl_drat", "disp_wt")
)

Note that the denominator wt was purposely in the data twice. Because using across function failed when there was a duplicating column name.

How to pass this list into the mtcars table and mutate the new column as in the alist above with each new column name as in newvar and the formula for mutating new column is numerator /denominator?

The desired output as below. Screenshot-2023-12-21-at-9-39-18-am.png

like image 445
user2360397 Avatar asked Oct 12 '25 16:10

user2360397


1 Answers

You could use with:

 mtcars %>%
    mutate(with(alist, set_names(.[numerator]/.[denominator], newvar)))

                   mpg cyl disp  hp drat    wt  qsec vs am gear carb   mpg_wt
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4 8.015267
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4 7.304348
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1 9.827586
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1 6.656299
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2 5.436047
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1 5.231214
                  cyl_drat   disp_wt
Mazda RX4         1.538462  61.06870
Mazda RX4 Wag     1.538462  55.65217
Datsun 710        1.038961  46.55172
Hornet 4 Drive    1.948052  80.24883
Hornet Sportabout 2.539683 104.65116
Valiant           2.173913  65.02890

In base R do:

cbind(mtcars,
    with(alist, setNames(mtcars[numerator]/mtcars[denominator], newvar)))
like image 170
KU99 Avatar answered Oct 14 '25 08:10

KU99