How can I delete all columns in an R dataframe whose names begin with X?
Here is how I want it to look (before and after):
Before:
¦ 1COL1 ¦ 2COL ¦ 3COL ¦ XCOL ¦ 4COL ¦ XXCOL ¦
After:
¦ 1COL1 ¦ 2COL ¦ 3COL ¦ 4COL ¦
You can delete the column whose name begin with X using grep and with its invert property set as TRUE. With invert = TRUE it returns the indices which don't match the given pattern.
df_1 <- df[grep("^X", colnames(df), invert = TRUE)]
This can also be done with grepl which returns logical vector.
df[!grepl("^X", colnames(df))]
 
    
    