Re: [R] comparing two matrices

From: Marc Schwartz <marc_schwartz_at_comcast.net>
Date: Sat 20 Jan 2007 - 23:06:30 GMT

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. Received on Sun Jan 21 10:10:47 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 - 10:30:22 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.