user1916067
user1916067

Reputation: 137

Efficient search of ordered vectors in a matrix

I have a matrix consisting of rows of ordered vectors:

v1 v2 v3 v4 v5 v6 v7 v8 v9 .... v45 v46 v47 v48
1  2  2  2  2  3  NA 3  3  ....  4   4   NA  NA
3  3  4  4  4  NA NA NA NA ....  5   NA  NA  NA
4  4  4  5  5  5  5  5  5  ....  NA  NA  NA  NA
...

I want to find an efficient way in R to subset records with an ordered vector (3,4) (i.e. a 3 before a 4) through the matrix using R such that

1  2  2  2  2  3  NA 3  3  ....  4   4   NA  NA
3  3  4  4  4  NA NA NA NA ....  5   NA  NA  NA

will be subsetted. If I subsetted a vector (1,2,3) (i.e. 1 before 2 and then 3), I will want to return this row:

1  2  2  2  2  3  NA 3  3  ....  4   4   NA  NA

Upvotes: 1

Views: 68

Answers (1)

CPak
CPak

Reputation: 13581

Maybe you want this?

set.seed(1)
data <- matrix(sample(1:10, 100, replace=TRUE), ncol=5)

searchfor <- c(1,2,3)
data[apply(data, 1, function(x) all(searchfor %in% x)),]

Output

[,1] [,2] [,3] [,4] [,5]   # empty

Another vector

searchfor <- c(7,8,9)
data[apply(data, 1, function(x) all(searchfor %in% x)),]

Output

     [,1] [,2] [,3] [,4] [,5]
[1,]    7    9    8    1    3
[2,]    5    7    1    9    8
[3,]    4    8    7    8    9

Data

      [,1] [,2] [,3] [,4] [,5]
 [1,]    3   10    9   10    5
 [2,]    4    3    7    3    8
 [3,]    6    7    8    5    4
 [4,]   10    2    6    4    4
 [5,]    3    3    6    7    8
 [6,]    9    4    8    3    3
 [7,]   10    1    1    5    8
 [8,]    7    4    5    8    2
 [9,]    7    9    8    1    3
[10,]    1    4    7    9    2
[11,]    3    5    5    4    3
[12,]    2    6    9    9    1
[13,]    7    5    5    4    7
[14,]    4    2    3    4    9
[15,]    8    9    1    5    8
[16,]    5    7    1    9    8
[17,]    8    8    4    9    5
[18,]   10    2    6    4    5
[19,]    4    8    7    8    9
[20,]    8    5    5   10    7

Upvotes: 2

Related Questions