r - R按最接近的日期合并两个数据框
问题描述
我有两个大数据框,dfA
并且dfB
,我在这里生成了简单的示例
dfA = data.frame(id=c("Apple", "Banana", "Carrot", "Dates", "Egg"),
Answer_Date=as.Date(c("2013-12-07", "2014-12-07", "2015-12-07", "2016-12-07", "2017-12-07" )),
x1 = c(1, 2, 3, 4, 5),
x2 = c(10, 20, 30, 40, 50))
Browse[2]> dfA
id Answer_Date x1 x2
1 Apple 2013-12-07 1 10
2 Banana 2014-12-07 2 20
3 Carrot 2015-12-07 3 30
4 Dates 2016-12-07 4 40
5 Egg 2017-12-07 5 50
dfB = data.frame(id=c("Apple", "Apple", "Banana", "Banana", "Banana"),
Answer_Date=as.Date(c("2013-12-05", "2014-12-07", "2015-12-10", "2018-11-07", "2019-11-07" )),
x3 = c(5, 4, 3, 2, 1),
x4 = c(50, 40, 30, 20, 10))
Browse[2]> dfB
id Answer_Date x3 x4
1 Apple 2013-12-05 5 50
2 Apple 2014-12-07 4 40
3 Banana 2014-12-10 3 30
4 Banana 2018-11-07 2 20
5 Banana 2019-11-07 1 10
我想按最接近的日期合并它们,以便我得到 dfA 和 dfB 中存在的项目,它们与id完全匹配,并且与 Answer_Date尽可能接近(即两个日期之间日期差的最小绝对值)。在这种情况下,我想得到
dfC
id Answer_Date.x Answer_Date.y x1 x2 x3 x4
1 Apple 2013-12-07 2013-12-05 1 10 5 50
2 Banana 2014-12-07 2014-12-10 2 20 3 30
不幸的是,与 merge() 苦苦挣扎并尝试了我在 StackOverflow 上找到的各种解决方案并没有解决我的问题,只会让我感到困惑。有人会向我指出正确的解决方案吗,最好简单解释一下它为什么起作用?
真诚的,并提前非常感谢
托马斯飞利浦
解决方案
左连接dfB
到dfA
,取每行日期之间的差异并选择每个 id 的最小差异。
left_join(dfA, dfB, by = "id") %>%
mutate(date_diff = abs(Answer_Date.x - Answer_Date.y)) %>%
group_by(id) %>%
filter(date_diff == min(date_diff)) %>%
select(id, Answer_Date.x, Answer_Date.y, starts_with("x"), date_diff)
然后输出是:
# A tibble: 2 x 8
# Groups: id [2]
id Answer_Date.x Answer_Date.y x1 x2 x3 x4 date_diff
<fct> <date> <date> <dbl> <dbl> <dbl> <dbl> <drtn>
1 Apple 2013-12-07 2013-12-05 1 10 5 50 2 days
2 Banana 2014-12-07 2014-12-10 2 20 3 30 3 days
顺便说一句,在您的示例代码Answer_Date
中,定义中的第三个dfB
应该是"2014-12-10"
而不是"2015-12-10"
.
推荐阅读
- vb.net - 无法将覆盖表单定位到父级的中心
- qt - QAbstractTableModel 更新背景颜色
- vue.js - 如何使用 Vue Js 为 Web 应用程序创建屏幕保护程序?
- django - Django - 在数据库中获取两个条目,一个为空,另一个包含所有数据
- api - 必应新闻搜索 API 返回截断的新闻名称
- javascript - 按给定的数字序列对 Javascript 数组进行排序
- c# - LINQ:选择表中每分钟的第一个值
- android - bottomsheetbehaviour 的生命周期事件是什么?
- python - 在python中解压缩压缩数据的代码?
- c# - Dynamics 365 CRM SDK 或 Rest API