[R] Adding duplicates by rows

Chuck Cleland ccleland at optonline.net
Mon Feb 26 18:51:06 CET 2007


Serguei Kaniovski wrote:
> Hi,
> 
> I am trying to add duplicates of matrix "mat" by row. Commands
> 
> subset(mat,duplicated(rownames(mat)))
> 
> or
> 
> mat[which(duplicated(rownames(mat))),]
> 
> return only half of the required indices. How can I find the remaining
> ones, ie the matches, so that I can add them up?

mat <- matrix(runif(70), ncol=5)
rownames(mat) <- c("Z", rep(LETTERS[1:6], each=2), "G")

  There is probably a more elegant way, but this seems to do what you want:

mat[rownames(mat) %in% names(which(table(rownames(mat)) > 1)),]

  Also, have you considered aggregate()?

aggregate(mat, list(ROW = rownames(mat)), sum)

> Thanks,
> Serguei
> 
> ___________________________________________________________________
> 
> Austrian Institute of Economic Research (WIFO)
> 
> Name: Serguei Kaniovski       P.O.Box 91
> Tel.: +43-1-7982601-231             Arsenal Objekt 20
> Fax: +43-1-7989386                  1103 Vienna, Austria
> Mail: Serguei.Kaniovski at wifo.ac.at  A-1030 Wien
> 
> http://www.wifo.ac.at/Serguei.Kaniovski
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch 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.

-- 
Chuck Cleland, Ph.D.
NDRI, Inc.
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894



More information about the R-help mailing list