0

I am trying to find out which two date values of a vector a specific date is between. I am not really sure how else to explain it, the example should help more.

## Vector of dates
temp <- seq(as.Date("2000/01/01"),as.Date("2003/01/01"),"years")
temp

[1] "2000/01/01" "2001/01/01" "2002/01/01" "2003/01/01"

date<- sample(seq(as.Date("2000/01/01"),as.Date("2003/01/01"),"days"),1)
date

This should be a random date, but just for the example let say that it is 2002/09/14. How can I go about having date look through temp and find the values that it is between, so for this example, the answer would be c("2002/01/01","2003/01/01").

I am basically looking for something that is the flip of the between function in dplyr.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Sam Edeus
  • 41
  • 6

1 Answers1

3

You can use findInterval

set.seed(123)
date<-sample(seq(as.Date("2000/01/01"),as.Date("2003/01/01"),"days"),1)
date
#[1] "2001-02-18"

ind <- findInterval(date, temp)
c(temp[ind], temp[ind + 1])
#[1] "2001-01-01" "2002-01-01"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213