data <- data.frame(Year = c( rep(2010, 3), 2011, rep(2012, 3) ), ID = c(13578, 13579, 13575, 13575, 13578, 13579, 13579), Rating = c(2, 1, 3, 4, 3, 2, 4)) data # Year ID Rating # 1 2010 13578 2 # 2 2010 13579 1 # 3 2010 13575 3 # 4 2011 13575 4 # 5 2012 13578 3 # 6 2012 13579 2 # 7 2012 13579 4
- Create a column equal to the current amount of
data$Rating , wheredata$Year < Yeardata$ID == ID
- This should calculate the total amount of ratings for each
ID up to the previous year.
The desired result will be
data
This can be done like this:
year <- 2014 # maximum year to include in cumsum ID.values <- names(table(data$ID)) # get unique values of data$ID, sorted # cumsum for 13575 rows, followed by cumsum for 13578 rows, ... Rating.cumsum <- unlist(sapply(ID.values, function(x) cumsum(data$Rating[data$ID == x]))) # assign cumsum output to appropriate rows data$cumsum[with(data, order(ID))] <- Rating.cumsum
nathanesau
source share