Carpa
Carpa

Reputation: 468

How to compare row-wise two different matrices exhaustively in R?

I have two matrices (mat1 and mat2) with the same number of columns (four each) and different number of rows (one matrix has three and the other one, five). I would like to compare every row in one matrix with every row in the other matrix. The values and the position in the row should be the same in both matrices. I have been trying the “apply” function but I got problems when defining the function: apply(mat2,1,function(x){mat1[x,]==mat2 [x,]} and other similar combinations result in the message “subscript out of bounds”. I am very new in this world (R and programming), have search information across the web but I didn’t find anything. I am really stuck. I would appreciate a lot your help. Thanks in advance. Carpa

> mat1
     [,1] [,2] [,3] [,4]
[1,]    2   44    3    9
[2,]   13   56   13   13
[3,]    4    9   14   33
> mat2
     [,1] [,2] [,3] [,4]
[1,]    1    6   11   16
[2,]    2    7   12   17
[3,]    3    8   13   18
[4,]    4    9   14   19
[5,]    5   10   15   20
> 
The output that I am looking for is:

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

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

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

Upvotes: 2

Views: 263

Answers (1)

Darren Tsai
Darren Tsai

Reputation: 35737

1. apply

array(apply(mat1, 1, function(x) t(x == t(mat2))), dim = c(dim(mat2), nrow(mat1)))

2. tapply

tapply(mat1, row(mat1), function(x) t(x == t(mat2)))

3. lapply

lapply(split(mat1, row(mat1)), function(x) t(x == t(mat2)))

Output

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

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

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

Upvotes: 1

Related Questions