Cardinal
Cardinal

Reputation: 228

remove certain vectors from a list

I want to remove certain vectors from a list. I have for example this:

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 in the list exampleList which contain both 1 and 5(so not only vectors which contain 1 or 5, but both). Thanks in advance!

Upvotes: 3

Views: 107

Answers (3)

jogo
jogo

Reputation: 12559

Here a solution with two steps:

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 variant without any definition of a new function

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

(... but it has two calls to apply-functions)

Upvotes: 3

andrew
andrew

Reputation: 2574

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 an element you want to keep in the list, and FALSE for an element you want to remove from the list. The second argument is just the list itself.

Upvotes: 5

Ronak Shah
Ronak Shah

Reputation: 388817

We can use sapply on every list element and remove those elements where both 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

Upvotes: 4

Related Questions