2

我想在我的自定义函数中创建一个段,其中参数“evars”的输入作为字符串返回,而不执行/评估参数。该参数是一个 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)}
} 

现在我希望它将参数作为字符串返回,而不执行它:

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

但是,现在它将返回:

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.

如何使函数返回参数“evars”的确切输入,而不执行它?

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

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

1 回答 1

2

我们可以使用match.call()和提取“evas”

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\"))"
于 2022-02-28T15:36:07.573 回答