'Generate a sequential counter based on a condition R

I'm working with a panel dataset and I need to create a sequential counter to identify time to and from an episode. The idea is to create a vector that will go from -2 to 5 years (with 0 being the year of the episode). The dataset looks like this

structure(list(country = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Bangladesh", 
"Barbados", "Benin", "Burundi", "Cameroon", "Chile", "Cyprus", 
"Ecuador", "Equatorial Guinea", "Gabon", "Ghana", "Guatemala", 
"Guinea", "Guyana", "Haiti", "India", "Jordan", "Lebanon", "Liberia", 
"Madagascar", "Mali", "Mexico", "Morocco", "Mozambique", "Nepal", 
"Nicaragua", "Niger", "Oman", "Pakistan", "Panama", "Papua New Guinea", 
"Peru", "Rwanda", "Senegal", "Seychelles", "Sierra Leone", "Singapore", 
"Sri Lanka", "Sudan", "Togo", "Tunisia", "Turkey", "Uganda", 
"Zambia", "Zimbabwe"), class = c("pseries", "factor")), date = structure(12:31, .Label = c("1965", 
"1966", "1967", "1968", "1969", "1970", "1971", "1972", "1973", 
"1974", "1975", "1976", "1977", "1978", "1979", "1980", "1981", 
"1982", "1983", "1984", "1985", "1986", "1987", "1988", "1989", 
"1990", "1991", "1992", "1993", "1994", "1995", "1996", "1997", 
"1998", "1999", "2000", "2001", "2002", "2003", "2004", "2005", 
"2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", 
"2014", "2015", "2016", "2017", "2018"), class = c("pseries", 
"factor")), oda_gdp_cyclical = c(-0.0324935877598818, -0.00752600677202254, 
0.0189276427016587, 0.0157818139406085, 0.0124581749631083, -0.00540096623366293, 
0.0277213961736074, -0.0212109456439322, 0.0042184336739809, 
-0.00749022185426284, -0.00583126153715459, 0.0109793841538662, 
-0.00802428451793625, 0.00528596069421613, 0.0179370088331591, 
7.18645244752135e-05, 0.000703793610724401, -0.0111594103693246, 
0.00294080442969348, -0.0142329769770062), episode = c(0L, 0L, 
1L, 1L, 1L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 
0L, 0L), epi_id = c(0, 0, 1, 1, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 
3, 0, 0, 0, 0, 0), output = c(-2, -1, 0, 1, 2, 3, 0, 1, 2, 3, 
4, 5, -2, -1, 0, 1, 2, 3, 4, 5)), class = "data.frame", row.names = c(NA, 
20L))

Where I managed to subset it, by selecting 2 years before and 5 years after the episode, using the function given in this post. I am aware that are some overlaps in between the episodes (i.e., the episodes are not all evenly apart) but this is of no importance. The variable I'm looking to generate is "output". In the case of overlapping, I would need to avoid the negatives (there are no negatives when coming to Bangladesh 1982) The idea is that "output"==0 for the first date in which episode==1. This should be done for each episode. Episodes are marked by "epi_id"

Any help is much appreciated!

Heading



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source