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

Create column from symbol in mutate (tidy eval)

所以我想创建一个名为 var 的新列,其中所有行的文本为 "testing"。 IE。结果应该像 mtcars$var <- "testing"。我尝试了不同的东西,例如 as_nameas_string...

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


  df %>% 
    mutate(var = hello)
}

f(mtcars)

我们可以做到:

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

f(mtcars)

但是,正如@Lionel Henry 所指出的(见下面的评论):

deparse will not check for simple inputs and might return a character vector. Then as_name() will fail if a length > 1 vector, or do nothing otherwise since it's already a string

as_name(substitute(hello)) does the same but checks the input is a simple symbol or string. It is more constrained than 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