[R] cum sums

Jim Lemon jim at bitwrit.com.au
Mon Mar 10 03:03:38 CET 2014


On 03/10/2014 05:57 AM, Philip A. Viton wrote:
>
> Suppose I have a dataframe beginning:
>
> id yr val
> a 1950 1
> b 1950 10
> a 1951 2
>
> I'm trying to produce a table of cumulative sums
> of val, disaggregated by id and then yr, so the result
> should begin
>
> id yr cumval
> a 1950 1
> a 1951 3
> b 1950 10
>
> I've been trying to do this using "aggregate"
> and passing the function "cumsum," but I can't get
> it to work. Can someone tell me how to do this?

Hi Philip,
Kinda messy, but try this:

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)
dfc<-by(df[,2:3],df$id,cumsum)
ids<-names(dfc)
dfcc<-cbind(rep(ids[1],dim(dfc[[1]])[1]),dfc[[1]])
names(dfcc)<-names(df)
for(n in 2:length(dfc)) {
  dfpc<-cbind(rep(ids[n],dim(dfc[[n]])[1]),dfc[[n]])
  names(dfpc)<-names(df)
  dfcc<-rbind(dfcc,dfpc)
}

Jim




More information about the R-help mailing list