[R] Computting statistics on a matrix with 2 factor column

Gavin Simpson gavin.simpson at ucl.ac.uk
Tue Jun 8 16:00:12 CEST 2004


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.
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%




More information about the R-help mailing list