Combining split () and cumsum ()

I am trying to create statistics for the cumulative goals of the season by a specific football player. I used the cut function to get the season from the dates of the game. I have data that matches this data file

df.raw <- data.frame(Game = 1:20, Goals=c(1,0,0,2,1,0,3,2,0,0,0,1,0,4,1,2,0,0,0,3), season = gl(4,5,labels = c("2001", "2002","2003", "2004"))) 

In real life, the number of games per season may not be constant

I want to get data that looks like

 df.seasoned <- data.frame(Game = 1:20,seasonGame= rep(1:5), Goals=c(1,0,0,2,1,0,3,2,0,0,0,1,0,4,1,2,0,0,0,3), cumGoals = c(1,1,1,3,4,0,3,5,5,5,0,1,1,5,6,2,2,2,2,5), season = gl(4,5,labels = c("2001", "2002","2003", "2004"))) 

With goals summarized throughout the year and game number during the season

+4
source share
3 answers

Another job for ddply and transform (from the plyr package):

 ddply(df.raw,.(season),transform,seasonGame = 1:NROW(piece), cumGoals = cumsum(Goals)) Game Goals season seasonGame cumGoals 1 1 1 2001 1 1 2 2 0 2001 2 1 3 3 0 2001 3 1 4 4 2 2001 4 3 5 5 1 2001 5 4 6 6 0 2002 1 0 7 7 3 2002 2 3 8 8 2 2002 3 5 9 9 0 2002 4 5 10 10 0 2002 5 5 11 11 0 2003 1 0 12 12 1 2003 2 1 13 13 0 2003 3 1 14 14 4 2003 4 5 15 15 1 2003 5 6 16 16 2 2004 1 2 17 17 0 2004 2 2 18 18 0 2004 3 2 19 19 0 2004 4 2 20 20 3 2004 5 5 
+5
source
  df.raw$cumGoals <- with(df.raw, ave(Goals, season, FUN=cumsum) ) df.raw$seasonGame <- with(df.raw, ave(Game, season, FUN=seq)) df.raw 

Or with a transform ... the original transform, i.e.:

 df.seas <- transform(df.raw, seasonGame = ave(Game, season, FUN=seq), cumGoals = ave(Goals, season, FUN=cumsum) ) df.seas Game Goals season seasonGame cumGoals 1 1 1 2001 1 1 2 2 0 2001 2 1 3 3 0 2001 3 1 4 4 2 2001 4 3 5 5 1 2001 5 4 6 6 0 2002 1 0 7 7 3 2002 2 3 8 8 2 2002 3 5 9 9 0 2002 4 5 10 10 0 2002 5 5 snipped 
+6
source

Here is a solution using data.table , which is very fast.

 library(data.table) df.raw.tab = data.table(df.raw) df.raw.tab[,list(seasonGame = 1:NROW(Goals), cumGoals = cumsum(Goals)),'season'] 
+5
source

All Articles