Lloyd Christmas
Lloyd Christmas

Reputation: 1038

Select columns by regex matching

I know there a lot of posts on this, but I couldn't find any that helped. What I'm trying to do is simple.

I want to select (or drop) columns based on whether a letter is present in a column name.

library(tibble)
library(stringr)
library(dplyr)

xy <- tibble("x" = 1:5, "123" = 6:10, "x123" = 11:15)

#does not have expected output
> xy %>% select(-matches("[:alpha:]"))
# A tibble: 5 x 3
      x `123`  x123
  <int> <int> <int>
1     1     6    11
2     2     7    12
3     3     8    13
4     4     9    14
5     5    10    15

But if I use str_view_all all the results are as expected, but doesn't work with the dplyr helper function matches for selecting columns.

str_view_all(x, "[:alpha:]")

enter image description here

I'm looking for a solution using stringr and dplyr if possible. It seems like this should be very straightforward.

Upvotes: 1

Views: 86

Answers (1)

acylam
acylam

Reputation: 18691

[:alpha:] is a POSIX character class that is only valid inside a bracketed expression. So you need an extra pair of brackets:

xy <- tibble("x" = 1:5, "123" = 6:10, "x123" = 11:15)

xy %>% select(-matches("[[:alpha:]]"))

Result:

# A tibble: 5 x 1
  `123`
  <int>
1     6
2     7
3     8
4     9
5    10

Upvotes: 1

Related Questions