Passing enquo expression to subfunction

140 Views Asked by At

This question is related to Passing variables to functions that use `enquo()`.

I have a higher function with arguments of a tibble (dat) and the columns of interest in dat (variables_of_interest_in_dat). Within that function, there is a call to another function to which I want to pass 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)
    }

What is the recommended way to pass variables_of_interest_in_dat to lower_function?

I have tried lower_function(dat, !!!variables_of_interest_in_dat) but when I run higher_function(mtcars, cyl) this returns "Error: Can't use !!! at top level."

In the related post, the higher_function did not enquo the variables before passing them to lower function.

Thank you

1

There are 1 best solutions below

3
On

Is this what you want?

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)

the {{}} (aka 'curly curly') operator replaces the approach of quoting with enquo()