dataframe - How to calculate product of lags for an arbitrary number of lags in R (dplyr) -


this elementary problem, don't seem working right. need calculate simple product of element , number of lags in r data.frame of time series data. trying achieve in dplyr pipe. e.g.:

require(dplyr)  df <- data.frame(year = c(2010, 2011, 2012, 2013, 2014),                  x = c(1, 2, 3, 4, 5))  dffinal <- df %>% mutate(prodlag1 = prod(x, lag(x, 1), na.rm = t),                          prodlag2 = prod(x, lag(x, 1), lag(x, 2), na.rm = t),                          prodlag3 = prod(x, lag(x, 1), lag(x, 2), lag(x, 3), na.rm = t)) 

the result not thought. e.g. prodlag1 resulting dataframe should this:

dffinal <- data.frame(year = c(2010, 2011, 2012, 2013, 2014),                       x = c(1, 2, 3, 4, 5),                       prodlag1 = c(na, 2, 6, 12, 20)) 

additionally, aiming @ lag = 10 , find more feasible way typing each individual lag in. reduce work this?

one way of doing prodlag10...

dffinal <- df %>% mutate(cumlog = cumsum(log(x)),                          prodlag10 = exp(cumlog-lag(cumlog,11))) 

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -