[R] Conditional Row Sum

Marc Schwartz (via MN) mschwartz at mn.rr.com
Thu Apr 20 21:02:07 CEST 2006


On Thu, 2006-04-20 at 11:46 -0700, Sachin J wrote:
> Hi,
>    
>   How can I accomplish this in R. Example:
>    
>   R1  R2
>   3     101
>   4     102
>   3     102
>   18    102
>   11    101
>    
>   I want to find Sum(101) =  14 - i.e SUM(R1) where R2 = 101
>                   Sum(102) = 25    - SUM(R2) where R2 = 102
>    
>   TIA
>   Sachin

Presuming that your data is in a data frame called DF:

> DF
  R1  R2
1  3 101
2  4 102
3  3 102
4 18 102
5 11 101

At least three options:

> with(DF, tapply(R1, R2, sum))
101 102
 14  25


> aggregate(DF$R1, list(R2 = DF$R2), sum)
   R2  x
1 101 14
2 102 25


> by(DF$R1, DF$R2, sum)
INDICES: 101
[1] 14
------------------------------------------------------
INDICES: 102
[1] 25


See ?by, ?aggregate and ?tapply and ?with.

HTH,

Marc Schwartz




More information about the R-help mailing list