让我澄清一下,我在这里不是在查看语法mutate_at或mutate(across(..., ...))类型。我只想知道如何在 tidyverse 管道语法中一次创建多个新列。
让我们假设数据集的情况iris。
我想创建 10 个(或 100 个或更多)具有这样的标准的新列。
V1是Petal.Length * 1,V2的是Petal.Length * 2V10 Petal.Length * 10无需明确编写每个列的名称和公式,如果我想创建 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
Run Code Online (Sandbox Code Playgroud)
在基础 R 中,这可以通过以下方式完成lapply:
df[paste0('col', value)] <- lapply(value, `*`, df$Petal.Length)
Run Code Online (Sandbox Code Playgroud)