Search code examples
rrlangquosure

How to filter components of a quosure by class


I want to filter out components of a function's argument by class, motivated by this question (which looks for a function f so that f(c(mpg, gear)) is equivalent to select(mtcars, mpg)).

One way to do so is:

    f0 <- \(x){
      names_in <- x |>  
        enquo() |>
        quo_get_expr()
       mtcars |> select(names_in[[2]]) ## !
      }

... but I need to pick the second component of c(mpg, gear), because the first is c. However, a user might want to call f0(mpg) only, so the first quosure component has to be used instead of the second.

My idea was to Filter the list of components returned by quo_get_expr and drop what evaluates to class function (here: in environment mtcars). While Mapping does return the expected list of booleans, Filtering actually Reduces the list of components to a nested function (treating mpg etc. as calls):


    f1 <- function(x){
      names_in <- enquo(x) |> quo_get_expr()
      is_no_function <- \(nm) !(nm |> eval(envir = mtcars) |> inherits('function'))
      list(map_result = Map(names_in, f = is_no_function),
           filter_result = Filter(names_in, f = is_no_function)
      )
    }

output:

## > f1(c(mpg, gear))
## $map_result
## $map_result[[1]]
## [1] FALSE
## 
## $map_result[[2]]
## [1] TRUE
## 
## $map_result[[3]]
## [1] TRUE
## 
## 
## $filter_result
## mpg(gear) 

expected output:

## ...
## $filter_result
## [1] mpg  gear

While the original question already has an elegant solution with tidyselect, I'd be grateful for a hint why Filtering behaves like it does in this example, and what would be the proper way to proceed with the enquo output.


Solution

  • I'm not sure the eval is really needed here. Do you intend to allow other functions like f1(sum(mpg, gear))? I think you can just more explictly work with the call and strip out the function.

    f2 <- function(x){
      names_in <- enquo(x) |> quo_get_expr()
      if (is.symbol(names_in)) {return(list(names_in))}
      stopifnot(is.call(names_in))
      names_in <- as.list(names_in)
      stopifnot(names_in[[1]]==quote(`c`))
      return(names_in[-1])
    }
    

    Which returns

    f2(c(mpg, gear))
    # [[1]]
    # mpg
    # [[2]]
    # gear
    
    f2(mpg)
    # [[1]]
    # mpg
    

    You get the unexpected result of mpg(gear) because what's being returned is a call object. See

    x <- f1(c(mpg,gear))
    class(x$filter_result)
    

    All call objects begin with a symbol for the function, then a list of their parameters. So if you have a list like

    as.call(list(quote(a), quote(b), quote(c)))
    # a(b, c)
    

    You can see it interprets the list as a call to the function a with parameters b and c