This question is a follow-up to a previous question: Click
In this question two data.frames are provided, since this question focuses on a more specific part, the example data is reduced.
tc <- textConnection('
ID Track4 Time Loc
4 50 40 1
5 55 50 1
6 55 60 1
')
MATCHINGS <- read.table(tc, header=TRUE)
tc <- textConnection('
ID Track4 Time Loc
"" 50 40 1
"" 55 10 1
"" 55 40 1
"" 55 59 1 ')
INVOLVED <- read.table(tc, header=TRUE)
In the previous question a solution was found to this problem: The goal is to place the least recent ID from MATCHINGS into INVOLVED by matching on Track1 and Loc. An extra condition is that the Time of the matching INVOLVED entry may not be higher than the Time of the entry in MATCHING. This was achieved with the current approach (see below)
A new constraint is that: the Time of the INVOLVED entry may not be more than 30 seconds (Time column is in seconds) lower than the MATCHINGS entry. Right now the following output is achieved:
ID Track4 Time Loc
4 50 40 1
5 55 10 1
5 55 40 1
6 55 59 1
The expected results are however:
ID Track4 Time Loc
4 50 40 1
"" 55 10 1
5 55 40 1
6 55 59 1
Since the Time of the INVOLVED entry is more than 30 seconds lower than the MATCHINGS entry that matches on Track4 and Loc. I do not see how to incorporate this in my current solution. According to Matthew Dowle a feature request in de data.table package is related to this issue, but it should already be possible to incoporate. Does anyone know how?
The current approach (Without taking the time constraint into account)
M = as.data.table(MATCHINGS)
I = as.data.table(INVOLVED)
M[,Time:=-Time]
I[,Time:=-Time]
setkey(M,Loc,Track4,Time)
I[,ID:={i=list(Loc,Track4,Time);M[i,ID,roll=TRUE,mult="first"]}][,Time:=-Time]
Update:
rollargument in data.table accepts finite roll backs and roll forwards since A LONG TIME. Just updating this post so that we can close #615.Also using the
on=argument implemented inv1.9.6.See history for the older answer if necessary.