I have dataframe that was created from the fusion of two dataframes. Both spanned over the same time intervall but contained different information. When I put them together, the info overlapped since there is no holes in the time interval of one of the dataframe. Here is an example where the rows “sp=A and B” are part of a first df and the rows “sp=C” come from a second. The first dataframe is continuous but the second consists of sporadic events. The resulting dataframe looks like this:
start end sp
2010-06-01 17:00:00 2010-06-01 19:30:00 A
2010-06-01 19:30:01 2010-06-01 20:00:00 B
2010-06-01 19:45:00 2010-06-01 19:55:00 C
2010-06-01 20:00:01 2010-06-01 20:30:00 A
2010-06-01 20:05:00 2010-06-01 20:10:00 C
2010-06-01 20:12:00 2010-06-01 20:15:00 C
2010-06-01 20:30:01 2010-06-01 20:40:00 B
2010-06-01 20:35:00 2010-06-01 20:40:10 C
2010-06-01 20:40:01 2010-06-01 20:50:00 A
I would like to prioritize “C” so when it overlaps the time interval of another “sp”, the time interval of “A” or “B” is cut accordingly. As seen in the example, I sometimes have multiple events of “C” that overlap a single event of “A” or “B”. The result would be this:
start end sp
2010-06-01 17:00:00 2010-06-01 19:30:00 A
2010-06-01 19:30:01 2010-06-01 19:44:59 B
2010-06-01 19:45:00 2010-06-01 19:55:00 C
2010-06-01 19:55:01 2010-06-01 20:00:00 B
2010-06-01 20:00:01 2010-06-01 20:04:59 A
2010-06-01 20:05:00 2010-06-01 20:10:00 C
2010-06-01 20:10:01 2010-06-01 20:11:59 A
2010-06-01 20:12:00 2010-06-01 20:15:00 C
2010-06-01 20:15:01 2010-06-01 20:30:00 A
2010-06-01 20:30:01 2010-06-01 20:34:59 B
2010-06-01 20:35:00 2010-06-01 20:40:10 C
2010-06-01 20:40:11 2010-06-01 20:50:00 A
My date/time columns are in POSIXct. Don’t hesitate to ask if something is unclear.
Thanks in advance
Here’s a nice way to do this with the
plyrpackage and a recursive function:Then you can do:
which gives you exactly what you want.
There might be some small bugs in the other cases, since your example data set doesn’t cover them all, but this is the general idea at least. Hope it helps. Good luck!