[R] Aggregate certain rows in a matrix
Dimitris Rizopoulos
d.rizopoulos at erasmusmc.nl
Mon Sep 6 16:47:12 CEST 2010
one way is the following:
M <- cbind(c(1,1,1,1,2,2,3,3,3,3), c(2,2,2,3,4,4,4,5,5,6),
c(1,2,3,4,5,6,7,8,9,10))
ind <- do.call(paste, c(as.data.frame(M[, 1:2], sep = "\r")))
M[, 3] <- ave(M[, 3], ind, FUN = "sum")
unique(M)
I hope it helps.
Best,
Dimitris
On 9/6/2010 4:29 PM, Kennedy wrote:
>
> 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
>
>
>
--
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center
Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014
More information about the R-help
mailing list