-2

I have a data frame like this:

colnames(df) <- c("A",  "B",  "C",  "MO_A",   "MO_B",   "D",   "F",  "MO_D")

Now I wanna remove all the columns that start with "MO_"

What is the best way to do that?

useR
  • 179
  • 3
  • 13
  • 3
    Possible duplicate of [How to drop columns by name pattern in R?](https://stackoverflow.com/questions/15666226/how-to-drop-columns-by-name-pattern-in-r) and [Subset data to contain only columns whose names match a condition](https://stackoverflow.com/questions/18587334/subset-data-to-contain-only-columns-whose-names-match-a-condition) – A. Suliman Aug 22 '18 at 20:27
  • 2
    Try `df[,!grepl('^MO_',colnames(df))]` – A. Suliman Aug 22 '18 at 20:27

2 Answers2

0

You could do:

for(n in colnames(df)) {
if(grepl("MO_", n)) df[[n]] <- NULL
}
SmitM
  • 1,366
  • 1
  • 8
  • 14
0

Use a regex to get the columns of interest then index the data frame with a negative index to remove them.

With a logical index:

df <- df[, !grepl('MO_', colnames(df))]

With a numeric index:

df <- df[, -grep('MO_', colnames(df))]
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
jadki
  • 482
  • 1
  • 8
  • 15