How to drop columns with column names that contain specific string?

Viewed 1440
 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")

4 Answers

Using dplyr:

library(dplyr)

df %>%
  select(-contains(c("epm", "enn", "jkk")))
#>    name agelk
#> 1   Jon    23
#> 2  Bill    41
#> 3 Maria    32

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

Using matches

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

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
Related