[英]Using `dplyr::mutate()` to create several new variables from names specified in a vector
I want to create several new empty variables in a dataframe where I specify the variable names in a vector.我想在数据框中创建几个新的空变量,我在其中指定向量中的变量名称。 This works if I only specify one variable name, but breaks with several.
如果我只指定一个变量名,但会中断多个变量名,则此方法有效。 I tried some previous solutions, but they didn't seem to work in this case, eg:
我尝试了一些以前的解决方案,但在这种情况下它们似乎不起作用,例如:
library(dplyr)
add_columns <- function(df, columns){
columns <- quo(columns)
mutate(df, !!columns := NA_character_)
}
columns <- c("x", "y")
iris %>%
add_columns(columns)
Error: The LHS of `:=` must be a string or a symbol
The desired output would be:所需的输出将是:
# A tibble: 150 x 7
Sepal.Length Sepal.Width Petal.Length Petal.Width Species x y
<dbl> <dbl> <dbl> <dbl> <fct> <chr> <chr>
1 5.10 3.50 1.40 0.200 setosa NA NA
2 4.90 3.00 1.40 0.200 setosa NA NA
3 4.70 3.20 1.30 0.200 setosa NA NA
4 4.60 3.10 1.50 0.200 setosa NA NA
5 5.00 3.60 1.40 0.200 setosa NA NA
6 5.40 3.90 1.70 0.400 setosa NA NA
7 4.60 3.40 1.40 0.300 setosa NA NA
8 5.00 3.40 1.50 0.200 setosa NA NA
9 4.40 2.90 1.40 0.200 setosa NA NA
10 4.90 3.10 1.50 0.100 setosa NA NA
# ... with 140 more rows
I wonder how can I make this work?我想知道我怎样才能使这项工作?
You don't need any quosures here because you are not dealing with quoted expressions.您在这里不需要任何 quosures,因为您没有处理引用的表达式。 Just create vectors with appropriate names and splice them in. Here I use the fact that vectors of length 1 are recycled, but you could also create vectors of full length:
只需创建具有适当名称的向量并将它们拼接起来。这里我使用了长度为 1 的向量被回收的事实,但您也可以创建全长向量:
add_columns <- function(df, columns){
new <- rep(NA_character_, length(columns))
names(new) <- columns
mutate(df, !!!new)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.