[R] cum sums

Jim Lemon jim at bitwrit.com.au
Mon Mar 10 05:27:43 CET 2014


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
>




More information about the R-help mailing list