Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove entire list elements which contain a certain string

Tags:

list

r

var1 is a list:

var1 <- list(c("tall tree", "fruits", "star"),  
             c("tree tall", "pine tree", "tree pine", "black forest", "water"), 
             c("apple", "orange", "grapes"), 
             c("ancient pine tree", "all trees"))

I need to remove those elements entirely from the list which contains the term "pine".

The desired answer is a list:

[[1]]
[1] "tall tree" "fruits"    "star"    
[[2]]
[1] "apple"  "orange" "grapes"

Thanks

like image 605
user6633625673888 Avatar asked May 25 '15 10:05

user6633625673888


2 Answers

You could try Filter here

Filter(function(x) !any(grepl("pine", x)), var1)
# [[1]]
# [1] "tall tree" "fruits"    "star"     
# 
# [[2]]
# [1] "apple"  "orange" "grapes"
like image 135
David Arenburg Avatar answered Sep 20 '22 13:09

David Arenburg


var1[lapply(var1,function(x) length(grep("pine",x,value=FALSE))) == 0]
like image 33
scoa Avatar answered Sep 17 '22 13:09

scoa