Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find previous hour and next hour in R

Suppose I pass "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?

like image 718
Pratik Patil Avatar asked Apr 26 '15 12:04

Pratik Patil


1 Answers

Assuming your time were a variable "X", you can use round or trunc.

Try:

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

This would still require some work to determine whether the values had actually been rounded up or down (for round). So, If you don't want to have to think about that, you can consider using 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"
like image 122
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 08 '22 18:10

A5C1D2H2I1M1N2O1R2T1