0

I have a data frame in R with 3 columns: start time, end time, and value

  start_time           end_time             value
 2017-01-03 00:00   2017-01-03 00:05         90
 2017-01-03 00:05   2017-01-03 00:10         89
 2017-01-03 00:10   2017-01-03 00:15         33
 2017-01-03 00:15   2017-01-03 00:20         55

another data frame is a list of time. For each time in the list, if the time is between start time and end time, return the value, if not return NA. Is there a way I can do this use foreach function?

Connie Chen
  • 113
  • 1
  • 15
  • Please see these links to create a better example of your problem: https://stackoverflow.com/help/mcve http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Rilcon42 May 17 '17 at 02:49

1 Answers1

0

You could do it using the base R cut.POSIXt() function. If your vector of times is e.g.:

library(lubridate)
df2 <- ymd_hm(c("2017-01-02 00:00", "2017-01-03 00:02", "2017-01-03 00:04", "2017-01-03 00:12")) # note that first one is not included

break2 <- unique(c(df$start_time, df$end_time))

cut.POSIXt(df2, breaks = break2, labels = c(df$value), right = TRUE)

[1] <NA> 90   90   33

NB:

  1. In this case, the breaks are easily obtained from your data frame as your intervals are mutually exclusive.
  2. In in this example the intervals are closed on the right (right = TRUE)
  3. In your case you don't define what will happen with values that are contained by two intervals e.g.: 2017-01-03 00:05.
Edgar Santos
  • 3,426
  • 2
  • 17
  • 29