Sample data (note: I used the lubridate library only for date processing)
library(lubridate) df <- data.frame( Date = dmy( c( "1/2/2013", "1/2/2013", "1/2/2013", "1/2/2013" , "1/2/2013", "1/2/2013", "1/3/2013", "1/3/2013", "1/3/2013" ) ), Symbol = c( "AA", "AA", "AA", "AAPL", "AAPL", "AAPL", "AA", "AA", "AA" ), Return = c( NA, 1.19, 0.89, NA, 0.22, 0.21, NA, -1.80, -0.52 ) )
Now, using dplyr , you can group_by your group_by and create the desired column:
library(dplyr) df %>% group_by(Date, Symbol) %>% mutate( Return_aux = ifelse( is.na(Return), 0, Return ), Cum_Sum = cumsum(Return_aux) )
Hooray!
Chuck ramirez
source share