Home > Mobile >  How to select columns if column names contain digits?
How to select columns if column names contain digits?

Time:01-22

With str_detect I am able to find out if column names contain digits, but it returns logical TRUE or FALSE. How do I use it to select columns instead?

Code

library(tibble)
library(dplyr)


data <- tribble(
  ~a1, ~b, ~c91, ~d,
  1, 2, 3, 4
)


data %>% 
  select(str_detect("[:digit:]", names(.)))

This returns this error

Error: Must subset columns with a valid subscript vector.
x Subscript has the wrong type `logical`.
i It must be numeric or character.

CodePudding user response:

dplyr comes with a set of helper functions to match column names in select.

You want:

data %>% 
  select(matches("[[:digit:]]"))

The issue here is that str_detect() returns a vector of booleans but select() expects column names.

  •  Tags:  
  • Related