Adding time to POSIXct object in R

I would like to add 1 hour to a POSIXct object, but it does not support '+'.

This command:

as.POSIXct("2012/06/30","GMT") 
    + as.POSIXct(paste(event_hour, event_minute,0,":"), ,"%H:%M:$S")

returns this error:

Error in `+.POSIXt`(as.POSIXct("2012/06/30", "GMT"), as.POSIXct(paste(event_hour,  :
    binary '+' is not defined for "POSIXt" objects

How can I add a few hours to a POSIXct object ?


POSIXct objects are a measure of seconds from an origin, usually the UNIX epoch (1st Jan 1970). Just add the requisite number of seconds to the object:

x <- Sys.time()
x
[1] "2012-08-12 13:33:13 BST"
x + 3*60*60 # add 3 hours
[1] "2012-08-12 16:33:13 BST"

The lubridate package also implements this nicely with convenience functions hours, minutes, etc.

x = Sys.time()
library(lubridate)
x + hours(3) # add 3 hours