3
 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").

Julian
  • 6,586
  • 2
  • 9
  • 33
Tpellirn
  • 660
  • 4
  • 11
  • Does this answer your question? [How to drop columns by name pattern in R?](https://stackoverflow.com/questions/15666226/how-to-drop-columns-by-name-pattern-in-r) – TarJae May 01 '21 at 14:08

4 Answers4

4

Using dplyr:

library(dplyr)

df %>%
  select(-contains(c("epm", "enn", "jkk")))
#>    name agelk
#> 1   Jon    23
#> 2  Bill    41
#> 3 Maria    32
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
PLY
  • 531
  • 2
  • 4
  • 18
4

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
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
  • 1
    Edited to ensure we drop as per OP and also to use `%like%` once for more efficiency. Revert edit if you prefer. – NelsonGon May 01 '21 at 13:21
3

Using matches

library(dplyr)
df %>%
   select(-matches('epm|enn|jkk'))
#   name agelk
#1   Jon    23
#2  Bill    41
#3 Maria    32
akrun
  • 874,273
  • 37
  • 540
  • 662
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
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
mischva11
  • 2,811
  • 3
  • 18
  • 34