I have a matrix such as this, [,1] [,2] [,3] [1,] 1 1 2 [2,] 2 5 5 and a larger matrix such as this, a b [1,] 1 5 [2,] 2 5 [3,] 4 9 [4,] 5 8 [5,] 7 8 [6,] 7 10 [7,] 9 10 what I want to do is check the number of times the columns in the first matrix appear as rows in the second matrix. So for instance in this example 1,5 and 2,5 appear in both so I'd want R to return the number 2. Is there a function to do this? -- View this message in context: http://www.nabble.com/matching-rows-in-matrices-tp24305831p24305831.html Sent from the R help mailing list archive at Nabble.com.
If A and B are first and second matrix respectively then try: rowSums(inner(A, t(B), identical)) where the generalized inner product, inner, is defined in this post: http://tolstoy.newcastle.edu.au/R/e4/help/08/08/19562.html On Thu, Jul 2, 2009 at 8:27 AM, dreamworx<Andy_woolston at hotmail.com> wrote:> > I have a matrix such as this, > > ? ? [,1] [,2] [,3] > [1,] ? ?1 ? ?1 ? ?2 > [2,] ? ?2 ? ?5 ? ?5 > > and a larger matrix such as this, > > ? ? a ?b > [1,] 1 ?5 > [2,] 2 ?5 > [3,] 4 ?9 > [4,] 5 ?8 > [5,] 7 ?8 > [6,] 7 10 > [7,] 9 10 > > what I want to do is check the number of times the columns in the first > matrix appear as rows in the second matrix. So for instance in this example > 1,5 ?and 2,5 appear in both so I'd want R to return the number 2. Is there a > function to do this? > -- > View this message in context: http://www.nabble.com/matching-rows-in-matrices-tp24305831p24305831.html > Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > R-help at r-project.org 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. >
On Jul 2, 2009, at 7:27 AM, dreamworx wrote:> > I have a matrix such as this, > > [,1] [,2] [,3] > [1,] 1 1 2 > [2,] 2 5 5 > > and a larger matrix such as this, > > a b > [1,] 1 5 > [2,] 2 5 > [3,] 4 9 > [4,] 5 8 > [5,] 7 8 > [6,] 7 10 > [7,] 9 10 > > what I want to do is check the number of times the columns in the > first > matrix appear as rows in the second matrix. So for instance in this > example > 1,5 and 2,5 appear in both so I'd want R to return the number 2. Is > there a > function to do this?My first approach would be to use merge(), which performs a relational join. So, given mat1: # Note the rownames here, to match the colnames in mat2 > mat1 [,1] [,2] a 1 2 b 5 5 and mat2: > mat2 a b [1,] 1 5 [2,] 2 5 [3,] 4 9 [4,] 5 8 [5,] 7 8 [6,] 7 10 [7,] 9 10 Using merge() we get: > merge(t(mat1), mat2) a b 1 1 5 2 2 5 This gives us the rows that match between the two matrices. Note that I transpose mat1 so that the structure matches that of mat2. Then just use nrow() to get a count: > nrow(merge(t(mat1), mat2)) [1] 2 See ?merge for more information. HTH, Marc Schwartz