Marc Mamin
2004-Jun-08 13:38 UTC
[R] Computting statistics on a matrix with 2 factor column
Hello, I suppose this is a basic question but couldn't find a solution.: I have a large matrix with let say 3 columns: V1 V2 V3 a x 2 a x 4 a y 8 b z 16 and I want to compute some statistics based on the levels resulting form the combination of the two first columns e.g.: SUM-> V1 V2 V3 a x 6 a y 8 b z 16 Thanks for your hints . Marc
Chuck Cleland
2004-Jun-08 13:44 UTC
[R] Computting statistics on a matrix with 2 factor column
?tapply ?aggregate You probably have a data frame, not a matrix. Marc Mamin wrote:> I suppose this is a basic question but couldn't find a solution.: > > I have a large matrix with let say 3 columns: > > V1 V2 V3 > a x 2 > a x 4 > a y 8 > b z 16 > > and I want to compute some statistics based on > the levels resulting form the combination of the two first columns > > e.g.: > > SUM-> > > V1 V2 V3 > a x 6 > a y 8 > b z 16-- Chuck Cleland, Ph.D. NDRI, Inc. 71 West 23rd Street, 8th floor New York, NY 10010 tel: (212) 845-4495 (Tu, Th) tel: (732) 452-1424 (M, W, F) fax: (917) 438-0894
Gavin Simpson
2004-Jun-08 14:00 UTC
[R] Computting statistics on a matrix with 2 factor column
Marc Mamin wrote:> Hello, > > I suppose this is a basic question but couldn't find a solution.: > > I have a large matrix with let say 3 columns: > > V1 V2 V3 > a x 2 > a x 4 > a y 8 > b z 16 > > and I want to compute some statistics based on > the levels resulting form the combination of the two first columns > > e.g.: > > SUM-> > > V1 V2 V3 > a x 6 > a y 8 > b z 16 > > > Thanks for your hints . > > Marc >?tapply and ?aggregate are two ways, with aggregate giving you something that more closely resembles what you asked for: > a <- factor(c("a","a","a","b")) > b <- factor(c("x","x","y","x")) > c <- c(2,4,8,16) > abc <- data.frame(a, b, c) > abc a b c 1 a x 2 2 a x 4 3 a y 8 4 b x 16 > tapply(abc$c, list(abc$a, abc$b), sum) x y a 6 8 b 16 NA > aggregate(abc$c, list(abc$a, abc$b), sum) Group.1 Group.2 x 1 a x 6 2 b x 16 3 a y 8 HTH Gavin -- %~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~% Gavin Simpson [T] +44 (0)20 7679 5522 ENSIS Research Fellow [F] +44 (0)20 7679 7565 ENSIS Ltd. & ECRC [E] gavin.simpson at ucl.ac.uk UCL Department of Geography [W] http://www.ucl.ac.uk/~ucfagls/cv/ 26 Bedford Way [W] http://www.ucl.ac.uk/~ucfagls/ London. WC1H 0AP. %~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%