首页 > 解决方案 > 从 mutate 中的符号创建列(整洁的评估)

问题描述

所以我想创建一个名为var所有行的文本“测试”的新列。即结果应该是这样的mtcars$var <- "testing"。我尝试过不同的东西,例如as_nameas_string...

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


  df %>% 
    mutate(var = hello)
}

f(mtcars)

标签: rdplyrrlangtidyeval

解决方案


我们可以做的:

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

f(mtcars)

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

deparse 不会检查简单的输入,可能会返回一个字符向量。然后 as_name() 如果长度 > 1 向量将失败,否则什么也不做,因为它已经是一个字符串

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

推荐阅读