[R] Sum with condition

David Winsemius dwinsemius at comcast.net
Wed Nov 2 20:13:55 CET 2011


On Nov 2, 2011, at 2:11 PM, Sarah Goslee wrote:

> Hi,
>
> On Wed, Nov 2, 2011 at 8:44 AM, Celine <bellard.celine at gmail.com>  
> wrote:

Celine. Please stop posting duplicates.


>> CELLCD AreaProtected
>>  8928      52.39389
>>  8928      41.91511
>>  8929      21.21975
>>  8929      63.65925
>>  8930      26.08547
>>  8930      14.04602
>
> You'll need to figure out how you want it to be combined with the
> original data frame, since there can't be empty cells, but:
>
>> dput(testdata)
> structure(list(CELLCD = c(8928L, 8928L, 8929L, 8929L, 8930L,
> 8930L), AreaProtected = c(52.39389, 41.91511, 21.21975, 63.65925,
> 26.08547, 14.04602)), .Names = c("CELLCD", "AreaProtected"), class =
> "data.frame", row.names = c(NA,
> -6L))
>>
>> aggregate(testdata$AreaProtected, by=list(CELLCD=testdata$CELLCD),  
>> FUN="sum")
> CELLCD        x
> 1   8928 94.30900
> 2   8929 84.87900
> 3   8930 40.13149

Or:
 > testdata$SumArea <- with(testdata, ave(AreaProtected, CELLCD,  
FUN=sum))
 > testdata
  CELLCD AreaProtected  SumArea
1   8928      52.39389 94.30900
2   8928      41.91511 94.30900
3   8929      21.21975 84.87900
4   8929      63.65925 84.87900
5   8930      26.08547 40.13149
6   8930      14.04602 40.13149

-- 
David Winsemius, MD
Heritage Laboratories
West Hartford, CT



More information about the R-help mailing list