[R] Aggregate certain rows in a matrix

Kennedy henrik.aldberg at gmail.com
Mon Sep 6 16:29:13 CEST 2010


Hi,

I have a matrix that looks like this 

  a <- c(1,1,1,1,2,2,3,3,3,3)
  b <- c(2,2,2,3,4,4,4,5,5,6)
  c <- c(1,2,3,4,5,6,7,8,9,10)
  M <- matrix(nr=10,nc=3)
  M[,1] <- a
  M[,2] <- b
  M[,3] <- c

> M
      [,1] [,2] [,3]
 [1,]    1    2    1
 [2,]    1    2    2
 [3,]    1    2    3
 [4,]    1    3    4
 [5,]    2    4    5
 [6,]    2    4    6
 [7,]    3    4    7
 [8,]    3    5    8
 [9,]    3    5    9
[10,]    3    6   10

I want to reduce the matrix according to the following: If the values of the
two first columns are the same in two or more rows the values in the third
column of the corresponding rows should be added and only one of the rows
should be keept. Hence the matrix M above should look like this

  1 2 6
  1 3 4
  2 4 11
  3 4 7
  3 5 17
  3 6 10


Thank you

Henrik



-- 
View this message in context: http://r.789695.n4.nabble.com/Aggregate-certain-rows-in-a-matrix-tp2528454p2528454.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list