[R] Sum by column

David Winsemius dwinsemius at comcast.net
Wed Jan 12 15:28:20 CET 2011


There are two functions you need to become familiar with:

?tapply
?ave

If you wanted these summed values to be placed in another column of  
the same dataframe, you would use ave. If you wanted a new structure  
(somewhat shorter) you would use tapply with sum as the function. E. g:

tapply(ecoregion$ED, ecoregion$ECOCODE, sum)

-- 
David.

On Jan 12, 2011, at 5:38 AM, Peter Francis wrote:

> Dear List,
>
> I have a question of convenience,
>
> I am looking to sum the values of one column based on another column  
> - a example may help explain better!
>
> ED			ECOCODE
> 21.809467	AA0101
> 36.229566	PA1201
> 51.861284	PA1201
> 11.36232	PA1201
> 27.264634	PA1201
> 12.261986	PA1201
> 46.519313	PA1201
> 7.815376	PA1201
> 2.810428	PA1201
> 13.478372	PA1201
> 35.670182	PA1301
> 27.128715	AT0801
> 19.010294	AT1201
> 15.475368	AT1201
> 18.597983	AT0101
> 29.292615	AT0101
> 6.749846	AT0101
> 14.981488	AT0101
> 14.93511	AT0101
> 14.93511	AT0101
> 21.040785	AT0101
> 8.271615	AT0101
> 12.94232	AT0101
> 6.749846	AT0101
> 15.484412	AT0101
> 29.644494	AT0101
> 43.211212	AT0101
>
> So for AA0101 it would be = 21.809467
> 	    AT1201 it would be = 19.010294+15.475368
>
> etc
>
> I would then like to be able to output a table with ECOCODE in one  
> column and the sum of ED in the other.
>
> This is stored in a dataframe called ecoregion, i understand people  
> like having code to change but i have none as i am a relative  
> beginner! Sorry in advance!
>
> Thanks
>
> Peter
>
> ______________________________________________
> R-help at r-project.org 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list