简体   繁体   English

如何使用 dplyr 中的 mutate 创建一系列由指定突变值的向量定义和调用的列?

[英]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).我想从 mtcars 数据集中取出一列“mpg”,并将它的每个值除以 1 到 100 之间的数字。这将创建 100 个新列(每个除数一列)。 The names of the columns should be "mpg_div_by_1", "mpg_div_by_2", "mpg_div_by_3".列的名称应为“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.我想我在某处读到 dplyr 1.0 可以以一种简单的方式做到这一点,所以我不必编写循环。

We could use map variants here.我们可以在这里使用map变体。

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 :要将其添加到原始数据帧中,我们可以使用bind_cols

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

This is much simpler in base R:这在基础 R 中要简单得多:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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