[R] Adding matrix rows that have the same name?

Henrique Dallazuanna wwwhsd at gmail.com
Tue Mar 23 22:24:22 CET 2010


Try this:

aggregate(as.data.frame(dum.mat.temp), list(row.names(dum.mat.temp)), sum)

On Tue, Mar 23, 2010 at 6:15 PM, Sarah Berke <skberke at gmail.com> wrote:
> Does anyone know if there is an R function that will take a matrix like this
>
> jim     1  0  0  0  0  0
> jim     0  1  0  0  0  0
> jim     0  0  1  0  0  0
> bob    1  0  0  0  0  0
> bob    0  0  1  0  0  0
> harry  0  0  1  0  0  0
> harry  0  0  0  1  0  0
> harry  0  0  0  0  1  0
> harry  0  0  0  0  0  1
>
> and make it like this? (that is, add together rows that have the same name?)
>
> jim    1 1 1 0 0 0
> bob   1 0 1 0 0 0
> harry 0 0 1 1 1 1
>
>
> here's the code I started with, if it helps
>
> library (dummies)
> a <- c(1,1,1,2,2,3,3,3,3)
> b<- c("A","B","C","A","C","C","D","E","F")
> name<- c("jim", "jim", "jim", "bob", "bob", "harry", "harry", "harry", "harry")
> MyMat <- cbind (a, b)
> rownames (MyMat) <- name
> dum.mat.temp <- dummy ("b", MyMat)
>       #dum.mat.temp <-cbind (name, dum.mat.temp) # if you want names
> as a column
> dum.mat.temp
>
> Many thanks in advance!
> --Sarah
>
> ______________________________________________
> 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.
>



-- 
Henrique Dallazuanna
Curitiba-Paraná-Brasil
25° 25' 40" S 49° 16' 22" O



More information about the R-help mailing list