-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?

2

2 Answers 2

0

You could do:

for(n in colnames(df)) {
if(grepl("MO_", n)) df[[n]] <- NULL
}
Sign up to request clarification or add additional context in comments.

Comments

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))]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.