Search code examples
rdplyrrlang

How to call function arguments inside tidyselect operators?


I am trying to create a function that relies on tidyselect operators. I am having trouble feeding non-string function arguments in there. I would appreciate any help trying to do this.

Here's an example of what I've tried to do using deparse(substitute(xvar)) to no avail.

library(tidyverse)

myfun <- function(xvar) {

new_df <- mtcars |>
       select(starts_with(deparse(substitute(xvar))), qsec)

return(new_df)
   

}

myfun(d) # variables that start with d and qsec


Solution

  • To feed in an object, ie, d (as opposed to the simple string, "d") in the user-defined function, you just need to define the deparse(substitute(xvar)) outside the starts_with:

    myfun <- function(xvar) {
      xx <- deparse(substitute(xvar))
      mtcars |>
        select(starts_with(xx), qsec)
    }
    myfun(d)
    
    #                      disp drat  qsec
    # Mazda RX4           160.0 3.90 16.46
    # Mazda RX4 Wag       160.0 3.90 17.02
    # Datsun 710          108.0 3.85 18.61
    # ...