Find the previous hour and next hour in R

Suppose I passed "2015-01-01 01:50:50" , then it should return "2015-01-01 01:00:00" and "2015-01-01 02:00:00" . How to calculate these values โ€‹โ€‹in R?

+6
source share
2 answers

Assuming your time was an "X" variable, you can use round or trunc .

Try:

 round(X, "hour") trunc(X, "hour") 

This will still require some work to determine if the values โ€‹โ€‹were really rounded or omitted (for round ). So, if you do not want to think about it, you can use the "lubridate" package:

 X <- structure(c(1430050590.96162, 1430052390.96162), class = c("POSIXct", "POSIXt")) X # [1] "2015-04-26 17:46:30 IST" "2015-04-26 18:16:30 IST" library(lubridate) ceiling_date(X, "hour") # [1] "2015-04-26 18:00:00 IST" "2015-04-26 19:00:00 IST" floor_date(X, "hour") # [1] "2015-04-26 17:00:00 IST" "2015-04-26 18:00:00 IST" 
+6
source

I would go with the next shell using the R base (you can specify your timezone using the tz argument in the strptime function)

 Myfunc <- function(x){x <- strptime(x, format = "%F %H") ; c(x, x + 3600L)} Myfunc("2015-01-01 01:50:50") ## [1] "2015-01-01 01:00:00 IST" "2015-01-01 02:00:00 IST" 
+5
source

Source: https://habr.com/ru/post/985993/


All Articles