lightsnail
lightsnail

Reputation: 788

To test whether a list match with another list in R

"a" and "b" are lists.

a<-list(matrix(c(0,2,0,0,0,2,0,0,1,0,0,0,0,0,2,1),4), matrix(c(0,1,0,0,0,2,1,0,0,0,1,0),3), matrix(c(0,0,0,0,2,0,1,0,0,0,0,0,2,0,2,1,0,1,2,0),5))
b<-list(matrix(c(2,2,1,1),1),matrix(c(1,2,1,2),1),matrix(c(2,1,2,1),1))

>a
[[1]]
     [,1] [,2] [,3] [,4]
[1,]    0    0    1    0
[2,]    2    2    0    0
[3,]    0    0    0    2
[4,]    0    0    0    1

[[2]]
     [,1] [,2] [,3] [,4]
[1,]    0    0    1    0
[2,]    1    0    0    1
[3,]    0    2    0    0

[[3]]
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    1
[2,]    0    1    0    0
[3,]    0    0    2    1
[4,]    0    0    0    2
[5,]    2    0    2    0

> b
[[1]]
     [,1] [,2] [,3] [,4]
[1,]    2    2    1    1

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

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

There both are three objects in list "a" and "b".

My aim is to test whether the non-zero elements in each row in the list "a" match with the corresponding position of corresponding object in list "b".

For example, the first object in "a" is:

 [[1]]
         [,1] [,2] [,3] [,4]
    [1,]    0    0    1    0
    [2,]    2    2    0    0
    [3,]    0    0    0    2
    [4,]    0    0    0    1

the first object in "b" is:

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

We can see the non-zero number in Row 1 of list "a" is 1, it locates at the third place of the row, and the third place of the first object in "b" is also 3, so we call it matched! The result should come out with a "TRUE".
The non-zero number in Row 2 of list "a" is 2 2 , they locate in the first and second place of the row, and the first and second place of the first object in "b" are also 2 2, so we call it matched! The result should also come out with a "TRUE". ...and so forth.

So the expected result should be:

[[1]]
     [,1] 
[1,]  TRUE   
[2,]  TRUE   
[3,] FALSE  
[4,]  TRUE

[[2]]
     [,1] 
[1,]  TRUE  
[2,] FALSE  
[3,]  TRUE   

[[3]]
     [,1] 
[1,]  TRUE   
[2,]  TRUE  
[3,]  TRUE   
[4,] FALSE  
[5,]  TRUE  

Upvotes: 0

Views: 172

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99391

Here's an idea. This checks each b vector against each row of the corresponding matrix in a, each with the zeros. A match is TRUE, and FALSE otherwise.

f <- function(x, y) {
    matrix(apply(x, 1, function(z) identical(y[z != 0], z[z != 0])))
}

Map(f, a, b)
# [[1]]
#       [,1]
# [1,]  TRUE
# [2,]  TRUE
# [3,] FALSE
# [4,]  TRUE
#
# [[2]]
#       [,1]
# [1,]  TRUE
# [2,] FALSE
# [3,]  TRUE
#
# [[3]]
#       [,1]
# [1,]  TRUE
# [2,]  TRUE
# [3,]  TRUE
# [4,] FALSE
# [5,]  TRUE

Upvotes: 2

Julius Vainora
Julius Vainora

Reputation: 48251

mapply(function(x, y) rowSums(!(t(t(x) == c(y)) | x == 0)) == 0, a, b)
# [[1]]
# [1]  TRUE  TRUE FALSE  TRUE
# 
# [[2]]
# [1]  TRUE FALSE  TRUE
#
# [[3]]
# [1]  TRUE  TRUE  TRUE FALSE  TRUE

Upvotes: 2

Related Questions