从mutate中的符号创建列(整洁的评估)

时间:2019-08-28 10:20:26

标签: r dplyr rlang tidyeval

因此,我想创建一个名为var的新列,所有行的文本均为“ testing”。即结果应类似于mtcars$var <- "testing"。我尝试了诸如as_nameas_string ...

library(tidyverse)    
f <- function(df, hello = testing){


  df %>% 
    mutate(var = hello)
}

f(mtcars)

1 个答案:

答案 0 :(得分:2)

我们可以做到:

f <- function(df, hello = testing){
  hello <- deparse(substitute(hello))
  df %>% 
    mutate(var =rlang::as_name(hello))
}

f(mtcars)
@pionel Henry指出的

但是(请参见下面的评论):

  

deparse将不会检查简单的输入,并且可能会返回字符向量。然后,如果长度> 1个向量,则as_name()将会失败,否则,否则它将不执行任何操作,因为它已经是字符串

     

as_name(substitute(hello))所做的相同,但检查输入的内容是简单的符号还是字符串。比as_label()更受限制

因此,最好将其重写为:

f <- function(df, hello = testing){
  hello <- as_label(substitute(hello))
  df %>% 
    mutate(var = hello )
}

或者:

f <- function(df, hello = testing){
  hello <- rlang::as_name(substitute(hello))
  df %>% 
    mutate(var = hello)
}

结果:

mpg cyl  disp  hp drat    wt  qsec vs am gear carb     var
1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4 testing
2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4 testing
3  22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1 testing
相关问题