Right now I use this line of code:
df <- df1 %>% dplyr:: select(grep("x", names(df1)), grep("y", names(df1)), grep("z", names(df1)))
I cannot figure out a way to do this without repeating the grep. It would be nice to feed grep a list or to create a peace of code where one does not have to copy and adjust the grep line. Any better ways to filter a data frame on column names containing part of a string?
>Solution :
You can use matches inside select, with a regular expression containing potential matches separated by |.
This means your existing code should be equivalent to
df <- df1 %>% select(matches('x|y|z'))
For example if df1 was this:
df1 <- data.frame(box = 1, yak = 2, lazy = 3, lab = 4, men = 5)
Then we can select columns whose names contain x, y or z by doing:
df1 %>%
select(matches('x|y|z'))
#> box yak lazy
#> 1 1 2 3
Created on 2023-09-19 with reprex v2.0.2