I am using multiple databases. For each of these databases I have created a key called matchcode
. This matchcode
is a combination of a country code and
Hope this works for you:
dfA[, yearA := year]
res1 <- dfA[dfB, on = .(iso, year), roll = 1, nomatch = 0]
res2 <- dfA[dfB, on = .(iso, year), roll = -1, nomatch = 0]
res <- rbind(res1, res2[yearA > year])
setnames(res, c('year', 'matchcode', 'i.matchcode'), c('yearB', 'matchcodeA', 'matchcodeB'))
# A B C D E F G iso yearB matchcodeA yearA K L M N O P Q matchcodeB
# 1: 1 0 0 0 1 0 1 NLD 2014 NLD2014 2014 1 0 0 0 1 0 1 NLD2014
# 2: 0 0 0 1 1 0 0 AUS 2011 AUS2010 2010 0 0 0 1 1 0 0 AUS2011
# 3: 1 0 1 0 0 1 0 AUS 2007 AUS2006 2006 1 0 1 0 0 1 0 AUS2007
# 4: 0 0 1 0 0 0 1 USA 2011 USA2010 2010 0 0 1 0 0 0 1 USA2010
# 5: 0 1 0 1 0 0 0 USA 2013 USA2012 2012 0 1 0 1 0 0 0 USA2013
# 6: 0 1 0 1 1 0 1 BEL 2009 BEL2008 2008 0 1 0 1 1 0 1 BEL2009
# 7: 0 1 1 1 0 1 0 NLD 2009 NLD2010 2010 0 1 1 1 0 1 0 NLD2009
# 8: 0 1 0 1 0 1 1 USA 2007 USA2008 2008 0 1 0 1 0 1 1 USA2007
# 9: 0 1 0 1 0 0 0 USA 2011 USA2012 2012 0 0 1 0 0 0 1 USA2010
# 10: 1 0 1 0 0 1 0 BLG 2007 BLG2008 2008 1 0 1 0 0 1 0 BLG2007
# 11: 1 0 1 0 0 1 0 BEL 2009 BEL2010 2010 0 1 0 1 1 0 1 BEL2009