Extract vectors from a list based on given elements

Viewed 59

Suppose I have vector v contains 6 elements and a list with a number of vectors, each vector has two elements the list has been generated from the matrix m as below:

v<-c(1,2,3,4,5,6)

m = matrix( c(1, 2, 10 , 2, 1, 3, 8 ,9,4,6,3,1,9,11,4,7,12,3,2,5),  ncol=2, byrow = TRUE) 

l <-tapply(m,rep(1:nrow(m),ncol(m)),function(i)i)
>  l
$`1`
[1] 1 2

$`2`
[1] 10  2

$`3`
[1] 1 3

$`4`
[1] 8 9

$`5`
[1] 4 6

$`6`
[1] 3 1

$`7`
[1]  9 11

$`8`
[1] 4 7

$`9`
[1] 12  3

$`10`
[1] 2 5

From the list l, I want to keep only the vectors which have the two elements in v

The result will be similar to:

>  R
 $`1`
 [1] 1 2

 $`2`
 [1] 1 3

 $`3`
 [1] 4 6

 $`4`
 [1] 3 1

 $`5`
 [1] 2 5 

The original list has 18835 vectors.

2 Answers

Here we use sapply with simplify=T to make a boolean vector that we can use to subset l. The assumptions I've made are that each list has two elements, but this could easily be changed by changing sum to all with minor edits.

l[sapply(l,function(x){sum(x %in% v)==2},simplify = T)]

We can use sapply to check if all the elements in x are present in v, assuming you have only 2 elements in each list element.

l[sapply(l, function(x) all(x %in% v))]


#$`1`
#[1] 1 2

#$`3`
#[1] 1 3

#$`5`
#[1] 4 6

#$`6`
#[1] 3 1

#$`10`
#[1] 2 5
Related