Skip to content
Prev 311694 / 398502 Next

Using cumsum with 'group by' ?

TheRealJimShady wrote
Peter Dalgaard's suggestion works for me ...

lines<-"id x date time
1 5 2012-06-05 12:01 
1 10 2012-06-05 12:02 
1 45 2012-06-05 12:03 
2 5 2012-06-05 12:01 
2 3 2012-06-05 12:03 
2 2 2012-06-05 12:05 
3 5 2012-06-05 12:03 
3 5 2012-06-05 12:04 
3 8 2012-06-05 12:05 
1 5 2012-06-08 13:01 
1 9 2012-06-08 13:02 
1 3 2012-06-08 13:03 
2 0 2012-06-08 13:15 
2 1 2012-06-08 13:18 
2 8 2012-06-08 13:20 
2 4 2012-06-08 13:21 
3 6 2012-06-08 13:15 
3 2 2012-06-08 13:16 
3 7 2012-06-08 13:17 
3 2 2012-06-08 13:18 
"

# read in data
dat1<-read.table(textConnection(lines), header=TRUE,stringsAsFactors=FALSE) 

# build csum variable
newdata <- transform(dat1, csum=ave(x, id, as.Date(date), FUN=cumsum)) 

# order data (not really necessary)
newdata.ord <-newdata[order(dat1[,"id"],dat1[,"date"],dat1[,"time"]),]

Or have I misinterpreted your request?

HTH

Pete (B not D)



--
View this message in context: http://r.789695.n4.nabble.com/Using-cumsum-with-group-by-tp4650457p4650556.html
Sent from the R help mailing list archive at Nabble.com.