Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to create a simple query to filter a data frame for different columns using part of column name

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading