4
 name <- c("Jon", "Bill", "Maria")
 agenn <- c(23, 41, 32)
 agelk <- c(23, 41, 32)
 agepm <- c(23, 41, 32)
 df <- data.frame(name, age,agelk,agepm)
 print (df)

I would like to drop columns with column names that contain c("epm","enn","jkk").

1

4 Answers 4

6

Using dplyr:

library(dplyr)

df %>%
  select(-contains(c("epm", "enn", "jkk")))
#>    name agelk
#> 1   Jon    23
#> 2  Bill    41
#> 3 Maria    32
Sign up to request clarification or add additional context in comments.

Comments

5

Using data.table and %like%

df[,!colnames(df) %like% paste0(c("epm","enn","jkkk"),collapse="|")]
   name agelk
1   Jon    23
2  Bill    41
3 Maria    32

1 Comment

Edited to ensure we drop as per OP and also to use %like% once for more efficiency. Revert edit if you prefer.
3

Using matches

library(dplyr)
df %>%
   select(-matches('epm|enn|jkk'))
#   name agelk
#1   Jon    23
#2  Bill    41
#3 Maria    32

Comments

2

Here a base R approach:

First of all your code ;)

name <- c("Jon", "Bill", "Maria")
agenn <- c(23, 41, 32)
agelk <- c(23, 41, 32)
agepm <- c(23, 41, 32)
df <- data.frame(name, agenn,agelk,agepm)

Create your values do drop:

drop_val <- c("epm","enn","jkk")

You can check with grepl if a string exists in another. So let's loop for every string you want to remove and compare if it exists in colnames(df). Well and if none of your strings fits, you keep them -> otherwise remove.

 df[!grepl(paste0(drop_val,collapse="|" ),names(df))]

Output:

   name agelk
1   Jon    23
2  Bill    41
3 Maria    32

1 Comment

Edited to remove for loops, and avoid explicit ==FALSE checks. Revert back if you please.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.