Re: [R] how to calculate another vector based on the data from a combination of two factors

From: hadley wickham <h.wickham_at_gmail.com>
Date: Sun, 16 Nov 2008 22:05:23 -0600

On Sun, Nov 16, 2008 at 8:12 PM, jeffc <hcen_at_andrew.cmu.edu> wrote:
>
> Hi,
>
> I have a data set similar to the following
>
> State Gender Quantity
> TX Male 1
> NY Female 2
> TX Male 3
> NY Female 4
>
>
> I need to calculate cumulative sum of the quantity by State and Gender. The
> expected output is
> State Gender Quantity CumQuantity
> TX Male 1 1
> TX Male 3 4
> NY Female 2 2
> NY Female 4 6
>
> I highly appreciate if someone can give me some hints on solving that in R.

Here's one approach that uses the plyr package:

library(plyr)
ddply(df, .(State, Gender), transform, CumQuantity = cumsum(Quantity))

You can find out more about how this works at http://had.co.nz/plyr

Hadley

-- 
http://had.co.nz/

______________________________________________
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.
Received on Mon 17 Nov 2008 - 04:09:16 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 17 Nov 2008 - 05:30:25 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive