Remove specific vectors from the list

I want to remove certain vectors from the list. I have, for example, the following:

a<-c(1,2,5)
b<-c(1,1,1)
c<-c(1,2,3,4)
d<-c(1,2,3,4,5)
exampleList<-list(a,b,c,d)

exampleList returns of course:
[[1]]
[1] 1 2 5

[[2]]
[1] 1 1 1

[[3]]
[1] 1 2 3 4

[[4]]
[1] 1 2 3 4 5

      

Is there a way to remove certain vectors from a list in R. I want to remove all vectors from listList that contain both 1 and 5 (so not only vectors containing 1 or 5, but both). Thanks in advance!

+3


source to share


3 answers


Use Filter

:

filteredList <- Filter(function(v) !(1 %in% v & 5 %in% v), exampleList)
print(filteredList)
#> [[1]]
#> [1] 1 1 1
#> 
#> [[2]]
#> [1] 1 2 3 4

      



Filter

uses a functional style. The first argument you pass is a function that returns TRUE

for the item you want to keep in the list and FALSE

for the item you want to remove from the list. The second argument is just a list.

+4


source


We can use sapply

for each element of the list and remove those elements where the values ​​1 and 5 are present.



exampleList[!sapply(exampleList, function(x) any(x == 1) & any(x == 5))]

#[[1]]
#[1] 1 1 1

#[[2]]
#[1] 1 2 3 4

      

+4


source


Here's a two-step solution:

exampleList<-list(a=c(1,2,5), b=c(1,1,1), c=c(1,2,3,4), d=c(1,2,3,4,5))
L <- lapply(exampleList, function(x) if (!all(c(1,5) %in% x)) x)
L[!sapply(L, is.null)]
# $b
# [1] 1 1 1
# 
# $c
# [1] 1 2 3 4

      

Here is a one-step option without defining a new function

exampleList[!apply(sapply(exampleList, '%in%', x=c(1,5)), 2, all)]

      

(... but it has two function-app calls)

+3


source







All Articles