Remove columns in data frame containing common character name

44 views Asked by At

I have a dataframe in r that has multiple columns with similar characters in the name, as an example:

  tom_wa = c(1,1,1);
  tom_ba = c(2,2,2);
  jim_wa = c(3,3,3);
  jim_ba = c(4,4,4);
  df <- data.frame(tom_wa, tom_ba, jim_wa, jim_ba)

The actual data frame has over 30 columns, is there a concise way where I can filter out columns only containing "_ba" or the "_wa"?

2

There are 2 answers

0
Jilber Urbina On BEST ANSWER
library(dplyr)
df %>% 
  select(ends_with(c("ba", "wa")))
0
Stibu On

With base R, you can do like this:

df[grep("_(b|w)a", names(df))]