1

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 ¦
Mus
  • 6,790
  • 22
  • 78
  • 117

1 Answers1

2

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))]
Ronak Shah
  • 355,584
  • 18
  • 123
  • 178