Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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

like image 491
Tpellirn Avatar asked Sep 02 '25 16:09

Tpellirn


2 Answers

Using dplyr:

library(dplyr)

df %>%
  select(-contains(c("epm", "enn", "jkk")))
#>    name agelk
#> 1   Jon    23
#> 2  Bill    41
#> 3 Maria    32
like image 170
PLY Avatar answered Sep 05 '25 09:09

PLY


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
like image 20
user14849686 Avatar answered Sep 05 '25 09:09

user14849686