I am trying to test a variety of conditions in a data.table that looks like this reproducible example
set.seed(17)
year <- 1980 + rnbinom(10000,3,0.35)
event <- rep(LETTERS, length.out=10000)
z <- as.integer(runif(10000,min = 0, max = 10))
dt <- data.table(event,year,z)
setkey(dt, event,year)
dt <- dt[,sum(z), by=c("event","year")]
V1 (which emerges from the last command) represents a count of event occurences.
So the data table is an ordered array and I need to execute a variety of functions on it. Here are some examples:
How do I calculate a rolling sum (or rolling mean) of the occurences in 10 prior years for each event? So for A 1990 the desired output is 1,452 (between 1980 and 1989). For H 2012, the output is 11 because between 2002 and 2011 there are only 11 occurences (3 in 2002, 3 in 2007, and 5 in 2010). For A 1983 the output is
NAHow can I check whether an event occurs in at least 12 out of 15 prior years? So for A 1997 we can see that the event occurred in more than 12 years in the 15 years prior (1982 - 1996, it happened in every year besides 1996) thus criterium met. However, for A 2001 we see that the event only occurs in 11 of 15 prior years (1986 - 2000), it does not happen in 1996,1998,1999,and 2000) criterium not met. The desired output here would be a discrete 1 (criterium met) or 0 (criterium not met)
Ideally the code would enable the calculation of both 1 and 2 not only for years that occur in the data.table but also for those between 1980 and 2013 that are missing. So for K 2005, we can calculate the outcome for Q1 as 25 (13 + 5 + 3 + 3 + 2) (thanks @Arun for pointing the former error out). For Q2, we see the event does not occur in 1999,2000,2001,2003, and 2004 hence the criterium "at least in 12 out of 15 years" is not met. Also, it is possible that the event-year combination exists in the data.table but that V1 has value 0 (see row 18, A 2001). Ideally, such zero occurences would be treated as non-occurences (e.g. by deleting all rows for which V1 is zero).
I know it's uncommon to post two questions but I feel they belong together and really relate to similar problems. Hope someone can make some suggestions.
Thanks a lot,
Simon
Z, 2012I understand the confusion. I have a dataset that actually goes to and includes 2013. But as the fake data show, the incidence of events decreases dramatically near the end. So in short Z, 2012 could exist in my data and requires a value, but I cannot go back further than 1980 hence every rolling mean before 1989 cannot have 10 years prior information. (Depending on the findings I will tweak this to 7 years or 8 or maybe 11)... Hope this clarifies it and thanks so much for your efforts! - SJDS