[R] Aggregate certain rows in a matrix

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Mon Sep 6 16:49:34 CEST 2010


On Mon, Sep 6, 2010 at 3:29 PM, Kennedy <henrik.aldberg at gmail.com> wrote:

> 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

Use library(plyr), convert to data frame, do ddply, convert back to
matrix if you want. I'm surprised mmply doesn't do it, but I dont
think it does:

 > Md=data.frame(M)
 > ddply(Md,c(1,2),function(r){sum(r[,3])})
  X1 X2 V1
1  1  2  6
2  1  3  4
3  2  4 11
4  3  4  7
5  3  5 17
6  3  6 10

plyr is on CRAN and that's the third time today I've told someone to use it.

Barry



More information about the R-help mailing list