Is there an R function to make subset by part of column name?

  • A+

I'm looking for a function in order to split a dataframe in several dataframe by the end of column names. To take an example :

Year | hour | LOT | S123_AA | S135_AA | S1763_BB | S173_BB | ... 

So I want to split it into 2 dataframes as:

Year | hour | LOT | S123_AA | S135_AA | 


Year | hour | LOT | S1763_BB | S173_BB | 

My key point is to conserve the first 3 columns and append all columns where the end names is _AA and _BB.

Thanks for your time


You can just take the right subset using grep.

df_AA = df[,c(1:3, grep("_AA$", colnames(df)))] df_BB = df[,c(1:3, grep("_BB$", colnames(df)))] 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: