[R] comparing two matrices

Dimitris Rizopoulos Dimitris.Rizopoulos at med.kuleuven.be
Sun Jan 21 09:56:54 CET 2007


based on Marc's approach, I think you can even use

which((mat2 %in% mat1)[1:nrow(mat2)])

instead of

which(apply(matrix(mat2 %in% mat1, dim(mat2)), 1, all))


I hope it helps.

Best,
Dimitris


Quoting Marc Schwartz <marc_schwartz at comcast.net>:

> On Sun, 2007-01-21 at 00:14 +0200, Adrian Dusa wrote:
>> Dear helpeRs,
>>
>> I have two matrices:
>> mat1 <- expand.grid(0:2, 0:2, 0:2)
>> mat2 <- aa[c(19, 16, 13, 24, 8), ]
>>
>> where mat2 is always a subset of mat1
>>
>> I need to find the corersponding row numbers in mat1 for each row in mat2.
>> For this I have the following code:
>>
>> apply(mat2, 1, function(x) {
>>     which(apply(mat1, 1, function(y) {
>>         sum(x == y)
>>         }) == ncol(mat1))
>>     })
>>
>> The code is vectorized, but I wonder if there is a simpler (hence faster)
>> matrix computation that I miss.
>>
>> Thank you,
>> Adrian
>
>
> I have not fully tested this, but how about:
>
> mat1 <- matrix(1:20, ncol = 4, byrow = TRUE)
> mat2 <- matrix(1:60, ncol = 4, byrow = TRUE)
> mat2 <- mat2[sample(15), ]
>
>> mat1
>      [,1] [,2] [,3] [,4]
> [1,]    1    2    3    4
> [2,]    5    6    7    8
> [3,]    9   10   11   12
> [4,]   13   14   15   16
> [5,]   17   18   19   20
>
>> mat2
>       [,1] [,2] [,3] [,4]
>  [1,]   13   14   15   16
>  [2,]    5    6    7    8
>  [3,]   41   42   43   44
>  [4,]   17   18   19   20
>  [5,]   21   22   23   24
>  [6,]   25   26   27   28
>  [7,]   53   54   55   56
>  [8,]    9   10   11   12
>  [9,]   57   58   59   60
> [10,]   33   34   35   36
> [11,]   49   50   51   52
> [12,]   45   46   47   48
> [13,]    1    2    3    4
> [14,]   29   30   31   32
> [15,]   37   38   39   40
>
>> which(apply(matrix(mat2 %in% mat1, dim(mat2)), 1, all))
> [1]  1  2  4  8 13
>
>
> HTH,
>
> Marc Schwartz
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>



Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm



More information about the R-help mailing list