【问题标题】:Passing enquo expression to subfunction将 enquo 表达式传递给子函数
【发布时间】:2021-11-21 06:47:30
【问题描述】:

这个问题与Passing variables to functions that use `enquo()`有关。

我有一个更高的函数,其中包含 tibble (dat) 和 dat 中感兴趣的列 (variables_of_interest_in_dat) 的参数。在该函数中,有一个对另一个函数的调用,我想将 variables_of_interest_in_dat 传递给该函数。

higher_function <- function(dat, variables_of_interest_in_dat){
    variables_of_interest_in_dat <- enquos(variables_of_interest_in_dat)

    lower_function(dat, ???variables_of_interest_in_dat???)
    }
    
lower_function <- function(dat, variables_of_interest_in_dat){
    variables_of_interest_in_dat <- enquos(variables_of_interest_in_dat)
       
    dat %>%
         select(!!!variables_of_interest_in_dat)
    }

variables_of_interest_in_dat 传递给lower_function 的推荐方式是什么?

我尝试过lower_function(dat, !!!variables_of_interest_in_dat),但是当我运行higher_function(mtcars, cyl) 时,这会返回“错误:无法在顶层使用!!!。”

在相关帖子中,higher_function 在将变量传递给lower 函数之前没有对变量进行enquo。

谢谢

【问题讨论】:

    标签: r tidyeval quasiquotes


    【解决方案1】:

    这是你想要的吗?

    library(tidyverse)
    
    LF <- function(df,var){
          newdf <- df %>% select({{var}})
          return(newdf)
        }
    
    HF <- function(df,var){
      LF(df,{{var}})
    }
    
    LF(mtcars,disp)  
    HF(mtcars,disp)
    

    {{}}(又名'curly curly')运算符用enquo()替换了引用的方法

    【讨论】:

    • 这行得通。但我仍然想知道如何/是否可以使用 enquo 来完成。在我真正的问题中,高级函数实际上使用...作为参数,然后是vars &lt;- enquos(..),并将vars 传递给低级函数。不确定如何将 {{ }} 与 ... 一起使用
    • 或者,您能否说明需要如何修改您的函数以使用HF(mtcars,vars(disp, mpg))
    • 它已经适用于HF(mtcars,c(disp, mpg))
    猜你喜欢
    • 2010-11-14
    • 2019-03-21
    • 2019-12-13
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    • 1970-01-01
    相关资源
    最近更新 更多