3

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!

0

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

One alternative is Filter(function(x) length(setdiff(c(1,5), x)) > 0, exampleList).
4

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 

3 Comments

or exampleList[!sapply(exampleList, function(x) all(c(1,5) %in% x) )]
@jogo yess and all this time I was trying with something like x %in% c(1, 5) which was definitely giving me incorrect results.
... and I was searching for a one-step variant of my answer :D
3

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.