r - How can I create sum of previous days but ignore the value at time t? -
i have df column t. want create columns t2 , t3
- t2 gives sum of t-2 , t-3
- t3 gives sum of t-2, t-3 , t-4 etc.
this dataframe
year t t2 t3 19620101 1 na na 19630102 2 na na 19640103 3 3 na 19650104 4 5 6 19650104 5 7 9 19650104 6 9 12 a different version of question here: how can create sum of previous days?
basically don't want use value @ time t in accumulation..
define roll function in terms of zoo's rollapplyr , use it. note rollapplyr width argument list(-seq(k)) means use indicated offsets. example, if k = 2 equals list(c(-1, -2)) means use values 1 , 2 prior.
library(zoo) roll <- function(t, k) rollapplyr(t, list(-seq(k)), sum, fill = na) transform(df, t2 = roll(t, 2), t3 = roll(t, 3)) an alternative this:
roll <- function(t, k) rollsumr(t, k+1, fill = na) - t giving:
year t t2 t3 1 19620101 1 na na 2 19630102 2 na na 3 19640103 3 3 na 4 19650104 4 5 6 5 19650104 5 7 9 6 19650104 6 9 12 note: used df:
df <- structure(list(year = c(19620101l, 19630102l, 19640103l, 19650104l, 19650104l, 19650104l), t = 1:6), .names = c("year", "t"), row.names = c(na, -6l), class = "data.frame")
Comments
Post a Comment