Home > other >  Remove column if contains partial string
Remove column if contains partial string

Time:02-01

This seems simple enough but I could not find a solution on this site. I would simply like to remove all columns from a dataframe if they contain a particular partial string match of "gs://". The table has 100's of columns and looks like this:

enter image description here

CodePudding user response:

Using this example data:

dat <- data.frame(
  x = c("gs://red", "orange"), 
  y = c("yellow", "gs://green"), 
  z = c("blue", "indigo")
)

dat
#          x          y      z
# 1 gs://red     yellow   blue
# 2   orange gs://green indigo

Index the dataframe using grepl():

dat[!sapply(dat, \(x) any(grepl("gs://", x)))]
#        z
# 1   blue
# 2 indigo

CodePudding user response:

alternatively with dplyr::select_if

library(dplyr)

dat %>% select_if(~!any(str_detect(.,'gs://')))

Created on 2023-01-31 with reprex v2.0.2

       z
1   blue
2 indigo

  • Related