R data.table join / subsetting / match by group and by condition

I am trying to multiply / match data by groups of 2 data.tables and cannot figure out how to do this in R. I have the following data table that has City_ID and timestamp (column name = time).

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")) 

I have a second data table with several city observations and timestamps (plus additional data). The table looks like this:

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)

Now I need to find observations for each city in the DT that have time> = time in another data table. table "schedule" (which basically corresponds to the table). Only those records should be saved (including columns that are not used for calculation, in the "other" column). The result I want is as follows:

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"))

I tried the following:

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, , , ).

+3
1

:

# 1) transform string to POSIXct object
DT[ , Time := as.POSIXct(strptime(Time, "%m-%d-%Y-%X"))]
timetable[ , Time := as.POSIXct(strptime(Time, "%m-%d-%Y-%X"))]

# 2) set key
setkey(DT, City_ID)
setkey(timetable, City_ID)

# 3) join tables
DT2 <- DT[timetable]

# 4) extract rows and columns
DT2[Time >= Time.1, names(DT), with = FALSE]

#    City_ID                Time Other
# 1:      12 2013-12-29 22:05:03     2
# 2:       9 2013-12-29 11:59:00     4
+3

All Articles