简体   繁体   中英

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". I think I read somewhere that dplyr 1.0 could do it in a straightforward way so I dont have to write a loop.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM