1

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.

1 Answer 1

1

[: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
Sign up to request clarification or add additional context in comments.

2 Comments

facepalm. okay that works brilliantly. Just curious why you don't need the extra bracket when using str_view_all for example.
@LloydChristmas Good question that I do not have an answer to. [:alpha:] is what is called a POSIX character class and will only be evaluated as such inside a bracketed expression [...]. [:alpha:] by itself would just mean that you're matching the characters :, a, l, p, h literally. This is why it puzzles me why your str_view_all example works in the first place.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.