Pavel Shliaha
Pavel Shliaha

Reputation: 935

How to use mutate from dplyr to create a series of columns defined and called by a vector specifying values for mutation?

I would like to take a column mpg from the mtcars dataset and divide each value of it by numbers from 1 to 100. This would create 100 new columns (one column per devisor). The names of the columns should be mpg_div_by_1, mpg_div_by_2, mpg_div_by_3 and so on. I think I read somewhere that dplyr could do it in a straightforward way so I don't have to write a loop.

Upvotes: 2

Views: 94

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389235

We could use map variants here.

library(purrr)
library(dplyr)

cols <- 1:5
map_dfc(cols, ~mtcars %>% transmute(!!paste0("mpg_div_by_", .x) := mpg / .x))

#   mpg_div_by_1 mpg_div_by_2 mpg_div_by_3 mpg_div_by_4 mpg_div_by_5
#1          21.0        10.50     7.000000        5.250         4.20
#2          21.0        10.50     7.000000        5.250         4.20
#3          22.8        11.40     7.600000        5.700         4.56
#4          21.4        10.70     7.133333        5.350         4.28
#5          18.7         9.35     6.233333        4.675         3.74
#....

To add it to original dataframes we can use bind_cols :

map_dfc(cols, ~mtcars %>% transmute(!!paste0("mpg_div_by_", .x) := mpg / .x)) %>%
      bind_cols(mtcars, .)

This is much simpler in base R :

mtcars[paste0("mpg_div_by_", cols)] <- lapply(cols, function(x) mtcars$mpg / x)

Upvotes: 2

Related Questions