自定义函数:Return 一个 tidyselect 参数作为字符串,不执行参数

Custom function: Return a tidyselect argument as character-string, without executing the argument

我想在我的自定义函数中创建一个段,其中参数“evars”的输入被 return 编辑为字符串,没有 executing/evaluating 参数。参数是一个 tidyselect 函数,用于从数据框中提取指定的列。

简化函数:

df <- data.frame(var1  = c("value_1", "value_2"),
                 var2.1 = c("value_1", "value_2"),
                 var2.2 = c("value_1", "value_2"),
                 var3 =  c("value_1", "value_2"))

customfunction <- function(df = df, evars = NULL){
   df2 <- df %>% select({{evars}}) 
   if(!is.null(evars)){paste(evars)}
} 

现在我想return将参数作为字符串,而不执行它:

> customfunction(df = df, evars = c("var1",contains("2")))
[1] "c("var1",contains("2"))"

但是,现在它将 return:

Error: `contains()` must be used within a *selecting* function.
i See <https://tidyselect.r-lib.org/reference/faq-selection-context.html>.
Run `rlang::last_error()` to see where the error occurred.

如何在不执行函数的情况下使函数 return 成为参数“evars”的准确输入?

问题似乎是由 tidyselect 函数 contains() 引起的,例如此代码不会导致错误:

> customfunction(df=df,evars=c("var1","var3"))
[1] "var1" "var3"

我们可以使用 match.call() 并提取 'evars'

customfunction <- function(df = df, evars = NULL){
   v1 <- match.call()$evars
   df2 <- df %>%
     select({{evars}}) 
     
     v1
  
   
} 

-测试

customfunction(df = df, evars = c("var1",contains("2")))
c("var1", contains("2"))

如果需要输出字符串,则用capture.output

换行
customfunction <- function(df = df, evars = NULL){
   v1 <- capture.output(match.call()$evars)
   df2 <- df %>%
     select({{evars}}) 
     
     v1
  
   
} 

customfunction(df = df, evars = c("var1",contains("2")))
[1] "c(\"var1\", contains(\"2\"))"