EDIT:
As divibisan notes, this question provides a range of general regex answers, which were tested on Python. I'm not sure works all of them apply in R. The highlighted answer is noted to be time-consuming; the most up-voted answer does not work directly on this example.
I'm trying to plug in an option for the user to select variables based on a regex in a custom function. The pattern should be optional, but I can't think of a foolproof default value.
library(dplyr)
my_select <- function(..., pattern = "") {
x <- enquos(...)
mtcars %>%
select(!!!x, matches(pattern))
}
my_select(cyl)
#> Error in matches(pattern): nchar(match) > 0 is not TRUE
NULL
or any other logical also gives an error because the regex argument passed to matches
must be a string.
#> Error in matches(pattern) : is_string(match) is not TRUE
For the moment, I'm going with " "
, as I presume it would be extremely rare... but it is certainly possible.
Is there a way around this or should I simply avoid matches
and write my own thing in base
?
Cheers!