Re: [R] comparing two matrices

From: Dimitris Rizopoulos <Dimitris.Rizopoulos_at_med.kuleuven.be>
Date: Sun 21 Jan 2007 - 08:56:54 GMT

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@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@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



R-help@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. Received on Sun Jan 21 20:01:56 2007

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Sun 21 Jan 2007 - 09:30:24 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.