我有两个国家*年份的数据集,涵盖相同的国家,但在不同的年份。我想合并这两者的方式,那一年是最接近的邻居,总是在国内(iso2code)。
第一个(dat1)看起来如下(这里只显示AT的头部,但iso2code有多个不同的值):
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第二个(dat2)如下所示:
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最后,我希望有这样的东西(请注意,2008年的国际刑警组织的价值可以与2010年和2006年相匹配,因为它与两者都是同样遥远的。)如果可能,我将选择最近的日期,如下所示):
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 不知道该怎么做。我很高兴有一个潮汐的解决方案,但真的,所有的帮助是非常感谢的!
发布于 2021-07-29 07:22:22
正如亨里克所提到的,这可以通过在滚动连接中更新到data.table包中可用的最近连接来解决。此外,如果匹配的距离相当遥远,则OP要求选择最近的日期。
library(data.table)
setDT(dat1)[setDT(dat2), roll = "nearest", on = c("iso2code", "year"),
`:=`(year.2 = i.year, affpol = i.affpol)]
dat1iso2code year elect\_polar\_lrecon year.2 affpol 1: AT 1999 2.48 NA NA 2: AT 2002 4.18 NA NA 3: AT 2006 3.66 2008 2.47 4: AT 2010 3.91 NA NA 5: AT 2014 4.01 2013 2.49 6: AT 2019 3.55 NA NA
此操作通过引用更新了dat1,即不通过添加两个额外列来复制整个数据对象。
现在,OP已经要求选择最近的日期,如果匹配是同样遥远的,但是联接已经选择了较早的日期。显然,在滚动连接到最近的地方没有控制这一点的参数。
解决方法是创建一个保持负年份的助手变量nyear,并加入该变量:
setDT(dat1)[, nyear := -year][setDT(dat2)[, nyear := -year],
roll = "nearest", on = c("iso2code", "nyear"),
`:=`(year.2 = i.year, affpol = i.affpol)][
, nyear := NULL]
dat1iso2code year elect\_polar\_lrecon year.2 affpol 1: AT 1999 2.48 NA NA 2: AT 2002 4.18 NA NA 3: AT 2006 3.66 NA NA 4: AT 2010 3.91 2008 2.47 5: AT 2014 4.01 2013 2.49 6: AT 2019 3.55 NA NA
发布于 2021-07-28 17:36:18
我是在朋友的帮助下想出来的。我把它留在这里以防其他人在找解决办法。假设第一个数据集是to_plot,第二个数据集称为to_plot2。然后:
find_nearest_year <- function(p_year, p_code){
years <- to_plot$year[to_plot$iso2code==p_code]
nearest_year <- years[1]
for (i in sort(years, decreasing = TRUE)) {
if (abs(i - p_year) < abs(nearest_year-p_year)) {
nearest_year <- i
}
}
return(nearest_year)
}
to_plot2 <- to_plot2 %>%
group_by(iso2code, year) %>%
mutate(matching_year=find_nearest_year(year, iso2code))
merged <- left_join(to_plot, to_plot2, by=c("iso2code", "year"="matching_year"))https://stackoverflow.com/questions/68563896
复制相似问题