使用 `dplyr::mutate()` 从向量中指定的名称创建几个新变量 [英] Using `dplyr::mutate()` to create several new variables from names specified in a vector

查看:43
本文介绍了使用 `dplyr::mutate()` 从向量中指定的名称创建几个新变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在数据框中创建几个新的空变量,在其中指定向量中的变量名称.如果我只指定一个变量名,但会中断多个变量名,则此方法有效.我尝试了一些以前的解决方案,但在这种情况下它们似乎不起作用,例如:

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, e.g.:

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

所需的输出是:

# 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?

推荐答案

这里不需要任何 quosures,因为您不处理带引号的表达式.只需创建具有适当名称的向量并将它们拼接起来即可.这里我使用了长度为 1 的向量被回收的事实,但您也可以创建全长向量:

You don't need any quosures here because you are not dealing with quoted expressions. 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:

add_columns <- function(df, columns){
  new <- rep(NA_character_, length(columns))
  names(new) <- columns
  mutate(df, !!!new)
}

这篇关于使用 `dplyr::mutate()` 从向量中指定的名称创建几个新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆