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
  • 7,290
  • 24
  • 86
  • 130

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))]
Chetan Arvind Patil
  • 854
  • 1
  • 11
  • 31
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213