Mock data:
set.seed(1)
df1 <- data.frame(country=c("US", "UK"),
year=c(2000, 2003))
df2 <- data.frame(country=rep(c("US", "UK"), 10),
year=rep(2000:2009, 2),
myvar=rnorm(20))
df1
contains the country-year of interest. I want to get the myvar
values for this country-year AND 3 years before and after.
In other words, the merging is done based on condition that df2$country==df1$country
AND df2$year > df1$year - 3 & df2$year < df1$year + 3
EDIT: My (working, not elegant) solution is to pad df1
to create all the country-years that I'm interested in, then merge with df2
the regular way.
library(plyr)
ddply(df1, c("country", "year"),
function(df) data.frame(rep(df$country, 7), (df$year-3):(df$year+3)))
produces
country year rep.df.country..7. X.df.year...3...df.year...3.
1 UK 2003 UK 2000
2 UK 2003 UK 2001
3 UK 2003 UK 2002
4 UK 2003 UK 2003
5 UK 2003 UK 2004
6 UK 2003 UK 2005
7 UK 2003 UK 2006
8 US 2000 US 1997
9 US 2000 US 1998
10 US 2000 US 1999
11 US 2000 US 2000
12 US 2000 US 2001
13 US 2000 US 2002
14 US 2000 US 2003