I want to repeat the values of one variable conditionally. For example, I have this data.frame
cod ano partido_prefeito
1 110001 1998 <NA>
2 110001 1999 <NA>
3 110001 2000 <NA>
4 110001 2001 PPB
5 110001 2002 <NA>
6 110001 2003 <NA>
7 110001 2004 <NA>
8 110001 2005 PDT
9 110001 2006 <NA>
10 110001 2007 <NA>
11 110001 2008 <NA>
12 110001 2009 PTN
13 110001 2010 <NA>
14 110001 2011 <NA>
15 110001 2012 <NA>
16 110001 2013 PMDB
17 110001 2014 <NA>
18 110001 2015 <NA>
19 110001 2016 <NA>
20 110002 1998 <NA>
For the variable "partido_prefeito" I have a lot of "NA" observations, however, I want to repeat the observation for the next 3 years, until the observation changes, for each "cod". Turning into something like that:
cod ano partido_prefeito
1 110001 1998 <NA>
2 110001 1999 <NA>
3 110001 2000 <NA>
4 110001 2001 PPB
5 110001 2002 PBP
6 110001 2003 PBP
7 110001 2004 PBP
8 110001 2005 PDT
9 110001 2006 PDT
10 110001 2007 PDT
11 110001 2008 PDT
12 110001 2009 PTN
13 110001 2010 PTN
14 110001 2011 PTN
15 110001 2012 PTN
16 110001 2013 PMDB
17 110001 2014 PMDB
18 110001 2015 PMBD
19 110001 2016 PMBD
20 110002 1998 <NA>
For the first 3 years: 1998, 1999, 2000, the data will still be "NA". The important detail is that I have a lot of observations with different "cod". How can I easily do this transformation?