我试图合并两个看起来像这样的数据框:
library(data.table)
#transactions
colNames<-c("id","tran")
df2 <- data.table(c("010","010","030","210","310","050"), as.Date(c("2012-12-28","2014-01-01","2011-07-05","2015-04-05","2013-07-05","2012-08-01")))
names(df2) <- colNames
#status change
colNames<-c("id","status")
df1 <- data.table(c("010","010","010","030","030","210","210","310","050"),
as.Date(c("2012-10-28","2013-11-01","2014-01-01","2011-05-09","2011-08-04","2013-07-06","2015-01-01","2013-05-04","2010-09-10")))
names(df1) <- colNames
df3
id tran status
1: 010 2012-12-28 2012-10-28
2: 010 2014-01-02 2014-01-01
3: 030 2011-07-05 2011-05-09
4: 210 2015-04-05 2015-01-01
5: 310 2013-07-05 2013-05-04
6: 050 2012-08-01 2010-09-10
基本上,所有交易都会在状态发生变化后的某个时刻发生。我试图将所有交易与每个ID的适当状态更改合并。棘手的部分是日期几乎不一样。 我需要每笔交易的状态更改日期 ...
我正在看?合并,但我不知道它是如何做到的那样。也许?聚合但是怎么知道聚合是以另一个数据帧为条件的呢?
谢谢!
答案 0 :(得分:2)
您可以简单地执行滚动连接。
df2[df1, status := i.status, on = .(id, tran = status), roll = -Inf]
df2
# id tran status
# 1: 010 2012-12-28 2012-10-28
# 2: 010 2014-01-01 2014-01-01
# 3: 030 2011-07-05 2011-05-09
# 4: 210 2015-04-05 2015-01-01
# 5: 310 2013-07-05 2013-05-04
# 6: 050 2012-08-01 2010-09-10
roll = -Inf
只是意味着对于df2
中的每个事件,我们希望匹配df1
中距离最近的较低事件,无论它有多远。status := i.status
表示我们希望通过引用(就地)在status
中创建一个名为df2
的列,同时借用{{1}中的匹配值}}。 df1$status
中位于i.
i
表中的列的df2
个州