Regex within dplyr/select helpers


I am trying to use regex (based on the new stringr cheat sheet) within my "select" to choose columns. However, it seems to not be working.

df1 %>% select(id, ends_with("\\d"))

is meant to select id, as well as every column that ends in a digit (0-9). However, it seems to just get id. I also tried wrapping it with brackets (and double brackets), but that doesn't help.

Additionally I tried

df1 %>% select(id, ends_with("[:digits:]"))

but that also seems to just give me id. (Additionally, I tried wrapping that in double brackets, but that did nothing).

Any suggestion on how to use regex within the select helpers like ends_with?



1 Like

The only select helper that allows regexes (from my brief read of the docs) is matches. Fortunately, the $ sign "anchors" the end of the string in a regex, so you should be able use that with matches.

df1 <- tribble(
  ~id, ~notselected, ~selected1, ~selected2,
  1, "a", "b", "c"

df1 %>% select(id, matches("\\d$"))
#> # A tibble: 1 x 3
#>      id selected1 selected2
#>   <dbl>     <chr>     <chr>
#> 1     1         b         c