Home > Back-end >  How to find the nearest time period within a vector of time objects?
How to find the nearest time period within a vector of time objects?

Time:06-07

I have a particular time period, and it dosen't match with any of the timeObject column within my dataframe. For example, say x (in the following section) is my column of timeObject. I want to find out the nearest time to y (in the following section).

x<-as.POSIXct(c("2018-10-26 00:00:43 NZDT" ,"2018-10-26 00:01:13 NZDT" ,"2018-10-26 00:01:43 NZDT" ,"2018-10-26 00:02:13 NZDT", "2018-10-26 00:02:43 NZDT" ,"2018-10-26 00:03:13 NZDT", "2018-10-26 00:03:43 NZDT", "2018-10-26 00:06:13 NZDT","2018-10-26 00:06:43 NZDT" ,"2018-10-26 00:07:13 NZDT") ,origin= "1970-01-01", tz=Sys.timezone())
y<-as.POSIXct("2018-10-26 00:01:12 NZDT", ,origin= "1970-01-01", tz=Sys.timezone())

I know I can simply subtract every value of x with y and find the minimum value. But is there a direct function for this?

CodePudding user response:

You may simply try

x[which.min(abs(x-y))]
  • Related