2
說一個數據表,我有兩個數據表dm
和dn
:R:在子集基於另一個
library(data.table)
set.seed(12)
dates = seq.Date(as.Date('2015-09-01'),as.Date('2015-11-01'), 2)
dm = data.table(user=sample(LETTERS[1:4], 10, replace=T),
time=sample(dates, 10))
dn = data.table(user=sample(LETTERS[1:8], 3, replace=F),
start=c(as.Date('2015-09-01'), as.Date('2015-10-05'),
as.Date('2015-09-14')),
end=c(as.Date('2015-10-30'), as.Date('2015-11-01'),
as.Date('2015-10-20')))
>dm
# user time
# 1: A 2015-09-25
# 2: D 2015-10-19
# 3: D 2015-09-21
# 4: B 2015-10-27
# 5: A 2015-09-15
# 6: A 2015-09-23
# 7: A 2015-10-21
# 8: C 2015-10-31
# 9: A 2015-10-01
# 10: A 2015-09-05
>dn
# user start end
# 1: B 2015-09-01 2015-10-30
# 2: F 2015-10-05 2015-11-01
# 3: A 2015-09-14 2015-10-20
一個該怎麼辦的基礎上dn
列於子集dm
?例如,對於dn
中的每個用戶,我們查找dm
查找匹配的user
,並查找user
的時間間隔[start
,end
](如果有)。
在這個例子中,期望的結果是
user time start end
5: A 2015-09-15 2015-09-14 2015-10-20
6: A 2015-09-23 2015-09-14 2015-10-20
9: A 2015-10-01 2015-09-14 2015-10-20
10: A 2015-09-05 2015-09-14 2015-10-20
4: B 2015-10-27 2015-09-01 2015-10-30
行號被保留只是爲了說明,和時間的順序並不重要。