我们可以在 tidyverse 中同时 create/mutate 几个新列吗

Can we create/mutate several new columns at once in tidyverse

让我澄清一下,我不是在看 mutate_atmutate(across(..., ...)) 类型的语法。我只想知道如何在 tidyverse 管道语法中同时创建多个新列。

让我们假设 iris 数据集的情况。

我想创建 10 个(或 100 个或更多)具有此类条件的新列。

没有明确地为这些列中的每一列写出名称和公式,如果我想创建 100 个新列,这可能很麻烦。

您可以使用 map 函数:

library(dplyr)
library(purrr)

df <- iris %>% head
value <- 1:5

bind_cols(df, 
     map_dfc(value, ~df %>% transmute(!!paste0('col', .x) := Petal.Length * .x)))

#  Sepal.Length Sepal.Width Petal.Length Petal.Width Species col1 col2 col3 col4 col5
#1          5.1         3.5          1.4         0.2  setosa  1.4  2.8  4.2  5.6  7.0
#2          4.9         3.0          1.4         0.2  setosa  1.4  2.8  4.2  5.6  7.0
#3          4.7         3.2          1.3         0.2  setosa  1.3  2.6  3.9  5.2  6.5
#4          4.6         3.1          1.5         0.2  setosa  1.5  3.0  4.5  6.0  7.5
#5          5.0         3.6          1.4         0.2  setosa  1.4  2.8  4.2  5.6  7.0
#6          5.4         3.9          1.7         0.4  setosa  1.7  3.4  5.1  6.8  8.5

在基础 R 中,这可以用 lapply 完成:

df[paste0('col', value)] <- lapply(value, `*`, df$Petal.Length)