jlk199
jlk199

Reputation: 137

Compare lists within matrix to another matrix in R

I have two matrices with the dimensions. Some of the cells within the matrices are NA, others are filled with a list of lists. If there is a list within a cell in Matrix 1, there will always be a list within the corresponding cell within Matrix 2.

What I need is another matrix that counts the number of times each item within each list of Matrix 1 is in the corresponding cell within Matrix 2.

Here are the matrices:

> matrix_1
     [,1]      [,2]     
[1,] NA            c(1001, 1002)
[2,] c(1001, 1003) NA       

> matrix_2
     [,1]                 [,2]     
[1,] NA                   c(1001, 1002, 1004)
[2,] c(1001, 1003, 1001)  NA     

Here is what I am looking for:

     [,1]    [,2]     
[1,] NA      2
[2,] 3       NA     

Cell [2,1] of the output matrix is 3, since 1003 occurred once and 1001 occurred twice within the corresponding list within Matrix 2 for this cell. Cell [1,2] of the output matrix is 2, since 1001 and 1002 both occurred once within corresponding cell of Matrix 2 for this cell.

Any ideas? I don't work with matrices a ton in R, so I am a bit lost. I could set this up as a dataframe, but figure a matrix might be easier/faster.

Here is the dput:

Matrix 1 = structure(list(NA, c(1001, 1003), c(1001, 1002), NA), .Dim = c(2L, 
2L))
Matrix 2 = structure(list(NA, c(1001, 1003, 1001), c(1001, 1002, 1004), 
    NA), .Dim = c(2L, 2L))

Upvotes: 2

Views: 54

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 101343

You can try the code below

res <- Matrix1
res[]<-Map(function(x,y) length(na.omit(match(x,y))),Matrix2,Matrix1)
res[is.na(Matrix1)] <- NA

such that

> res
     [,1] [,2]
[1,] NA   2   
[2,] 3    NA

Upvotes: 2

Related Questions