I have two country*year level datasets that cover the same countries but in different years. I would like to merge the two in a way that year is matched with its nearest neighbor, always within country (iso2code).
The first (dat1) looks like this (showing here only the head for AT, but iso2code has multiple different values):
iso2code year elect_polar_lrecon
<chr> <dbl> <dbl>
1 AT 1999 2.48
2 AT 2002 4.18
3 AT 2006 3.66
4 AT 2010 3.91
5 AT 2014 4.01
6 AT 2019 3.55
The second (dat2) looks like this:
iso2code year affpol
<chr> <dbl> <dbl>
1 AT 2008 2.47
2 AT 2013 2.49
3 DE 1998 2.63
4 DE 2002 2.83
5 DE 2005 2.89
6 DE 2009 2.09
In the end I would like to have something like (note that the value of affpol for 2008 could be matched both with 2010 and with 2006 as it is equally distant from both. If possible, I would go for the most recent date, as it is below):
iso2code year.1 elect_polar_lrecon year.2 affpol
<chr> <dbl> <dbl> <dbl> <dbl>
1 AT 1999 2.48
2 AT 2002 4.18
3 AT 2006 3.66
4 AT 2010 3.91 2008 2.47
5 AT 2014 4.01 2013 2.49
6 AT 2019 3.55
Not sure about how to do this... I am happy for a tidyverse solution, but really, all help is much appreciated!