I'm trying to fill in missing year values by a group both incrementally and decrementally when I know that each increment/decrement should be 1. Here's a reproducible example. Note there are two ids where the first id starts in 2002 (although it's missing) and the second id starts in 2007 (again also missing). I know this from the existing year and the fact that the increment/decrement should be 1.
id <- rep(c("01012895", "01021890"), each = 6)
value <- c(rnorm(12))
year <- c("NA", "NA", 2004, "NA", "NA", 2007, "NA", "NA", "NA", 2010, "NA", "NA")
df <- data.frame(id, value, year)
df
id value year
1 01012895 -1.05853432 NA
2 01012895 0.06480395 NA
3 01012895 -3.32811206 2004
4 01012895 -0.33427578 NA
5 01012895 -0.22790538 NA
6 01012895 1.46991465 2007
7 01021890 -0.65928777 NA
8 01021890 -0.25701765 NA
9 01021890 1.24331689 NA
10 01021890 0.10006530 2010
11 01021890 -0.83971071 NA
12 01021890 1.15893263 NA
df2 is what I want eventually.
year2 <- c(2002:2007, 2007:2012)
df2 <- data.frame(id, value, year2)
I've tried to find a get around using fill, like in df3, but it only carries existing values without an option to alter it.
df3 <- df %>% group_by(site_no) %>% fill(year, .direction = "updown")