select columns based on multiple strings with dplyr contains()

RRegexDplyrMatchingMultiple Matches

R Problem Overview


I want to select multiple columns based on their names with a regex expression. I am trying to do it with the piping syntax of the dplyr package. I checked the other topics, but only found answers about a single string.

With base R:

library(dplyr)    
mtcars[grepl('m|ar', names(mtcars))]
###                      mpg am gear carb
### Mazda RX4           21.0  1    4    4
### Mazda RX4 Wag       21.0  1    4    4

However it doesn't work with the select/contains way:

mtcars %>% select(contains('m|ar'))
### data frame with 0 columns and 32 rows

What's wrong?

R Solutions


Solution 1 - R

You can use matches

 mtcars %>%
        select(matches('m|ar')) %>%
        head(2)
 #              mpg am gear carb
 #Mazda RX4      21  1    4    4
 #Mazda RX4 Wag  21  1    4    4

According to the ?select documentation

> ‘matches(x, ignore.case = TRUE)’: selects all variables whose name matches the regular expression ‘x’

Though contains work with a single string

mtcars %>% 
       select(contains('m'))

Solution 2 - R

You can use contains from package dplyr, if you give a vector of text options, like this:

mtcars %>% 
       select(contains(c("m", "ar"))

Solution 3 - R

You could still use grepl() from base R.

df <- mtcars[ , grepl('m|ar', names(mtcars))]

...which returns a subset dataframe, df, containing columns with m or ar in the column names

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionagenisView Question on Stackoverflow
Solution 1 - RakrunView Answer on Stackoverflow
Solution 2 - RNicki NorrisView Answer on Stackoverflow
Solution 3 - RMuthoni Thiong'oView Answer on Stackoverflow