R data.table联接/子集/按组和条件进行匹配

问题描述 投票:3回答:1

我正在尝试按2个data.tables中的组对数据进行子集/匹配,但无法弄清楚R中的情况。我有以下具有City_ID和时间戳(列名=时间)的data.table。

Library(data.table)  
timetable <- data.table(City_ID=c("12","9"),
                        Time=c("12-29-2013-22:05:03","12-29-2013-11:59:00")) 

我有第二个data.table,其中包含对城市和时间戳的多次观察(加上其他数据)。该表如下所示:

DT = data.table(City_ID =c("12","12","12","9","9","9"),
                Time= c("12-29-2013-13:05:13","12-29-2013-22:05:03",
                        "12-28-2013-13:05:13","12-29-2013-11:59:00",
                        "01-30-2013-10:05:03","12-28-2013-13:05:13"), 
                Other=1:6)

现在,我需要在其他data.table“ timetable”(基本上是matchtable)中找到DT中每个具有时间> = Time的城市的观测值。仅应保留那些记录(包括不用于计算的列;在示例列“ other”中)。我想要的结果看起来像这样:

desiredresult = data.table(City_ID=c("12","9"),
                           Time= c("12-29-2013-22:05:03","12-29-2013-11:59:00"),
                           Other=c("2","4"))

我尝试了以下操作:

setkey(DT, City_ID, Time)  
setkey(timetable, City_ID)  
failedresult = DT[,Time >= timetable[Time], by=City_ID]  
failedresult2 = DT[,Time >= timetable, by=City_ID]  

BTW:我知道最好另外分割日期和时间,但这可能会使示例变得更加复杂(并且当我测试通过data.table在时间戳中找到最小值时,它似乎起作用了。) >

我正在尝试按2个data.tables中的组对数据进行子集/匹配,并且无法弄清楚R中的情况。我有以下data.table,其中包含City_ID和时间戳(列名= Time)。 ...

r match data.table subset
1个回答
3
投票

这是此任务的一种方法:

© www.soinside.com 2019 - 2024. All rights reserved.