我想使用dplyr
在数据框中添加多列(填充NA
)。我已经用一个字符向量定义了这些列的名称。通常,只需添加一列时,可以使用以下模式:
test %>%
mutate(!!new_column := NA)
然而,我无法将其与across
一起使用:
library(dplyr)
test <- data.frame(a = 1:3)
add_cols <- c("col_1", "col_2")
test %>%
mutate(across(!!add_cols, ~ NA))
#> Error: Problem with `mutate()` input `..1`.
#> x Can't subset columns that don't exist.
#> x Columns `col_1` and `col_2` don't exist.
#> ℹ Input `..1` is `across(c("col_1", "col_2"), ~NA)`.
test %>%
mutate(!!add_cols := NA)
#> Error: The LHS of `:=` must be a string or a symbol
expected_output <- data.frame(
a = 1:3,
col_1 = rep(NA, 3),
col_2 = rep(NA, 3)
)
expected_output
#> a col_1 col_2
#> 1 1 NA NA
#> 2 2 NA NA
#> 3 3 NA NA
这段内容是通过reprex包 (v1.0.0)在2021-10-05创建的。
第一种方法正确地创建了列名,但它会直接尝试在现有的列名中查找。第二种方法中,我只能使用单个字符串。
是否有tidyverse解决方案,还是需要使用传统的for循环?
mutate
/across
这样做。 - starja