[R] cum sums

Ista Zahn istazahn at gmail.com
Mon Mar 10 12:46:47 CET 2014


Another option is

library(plyr)
ddply(df, "id", transform, valCS = cumsum(val))

Best,
Ista

On Mon, Mar 10, 2014 at 12:27 AM, Jim Lemon <jim at bitwrit.com.au> wrote:
> In fact, I erred by summing both the year and the value, so i would
> recommend Peter's (much less messy) solution.
>
> Jim
>
>
> On 03/10/2014 02:57 PM, Peter Alspach wrote:
>>
>> Tena koe Philip
>>
>> An alternative to Jim's solution which seems to work and you may, or may
>> not, find less messy:
>>
>> df<- read.table(text="id yr val
>> a 1950 1
>> b 1950 10
>> a 1951 2
>> b 1952 3
>> c 1952 4
>> a 1954 5
>> b 1954 2
>> c 1954 3",header=TRUE)
>> df1<- df[order(df$id, df$yr),]
>> df1$valCS<- unlist(by(df1$val, df1$id, cumsum))
>> df1
>>
>> If you need to get back to the original order you can sort by row.names.
>>
>> HTH ....
>>
>> Peter Alspach
>>
>
> ______________________________________________
> 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.




More information about the R-help mailing list