1

I often create a "vector" of the variables I use most often while I'm coding. Usually if I just input the vector object in select it works perfectly. Is there any way I can use in the helper functions in a string?

For example I could do

library(dplyr)

x = c('matches("cyl")')

mtcars %>% 
  select_(x)

but this is not preferable because 1) select_ is deprecated and 2) it's not scalable (i.e., x = c('hp', 'matches("cyl")') will not grab both the relevant columns.

Is there anyway I could use more tidyselect helper functions in as part of a vector?

Note: if I do something like:

x = c(matches("cyl"))
#> Error: `matches()` must be used within a *selecting* function.
#> ℹ See <https://tidyselect.r-lib.org/reference/faq-selection-context.html>.

I get an error, so I'll definitely need to enquo it somehow.

Edward
  • 10,360
  • 2
  • 11
  • 26
John-Henry
  • 1,556
  • 8
  • 20

1 Answers1

2

You are trying to turn a string into code which might not be the best approach. However, you can use parse_exprs with !!!.

library(dplyr)
library(rlang)

x = c('matches("cyl")')
mtcars %>% select(!!!parse_exprs(x))

#                    Cyl
#Mazda RX4             6
#Mazda RX4 Wag         6
#Datsun 710            4
#Hornet 4 Drive        6
#Hornet Sportabout     8
#...

x = c('matches("cyl")', 'hp')
mtcars %>% select(!!!parse_exprs(x))

#                    cyl  hp
#Mazda RX4             6 110
#Mazda RX4 Wag         6 110
#Datsun 710            4  93
#Hornet 4 Drive        6 110
#Hornet Sportabout     8 175
#....
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213