17

I have data in the format

time <-  c("16:53", "10:57", "11:58")

etc

I would like to create a new column where each of these times is rounded to the nearest hour. I cannot seem to get the POSIX command to work for me.

as.character(format(data2$time, "%H:%M"))

Error in format.default(structure(as.character(x), names = names(x), dim = dim(x), : invalid 'trim' argument

Let alone use the round command. Can anyone advise?

petermeissner
  • 12,234
  • 5
  • 63
  • 63
user1558387
  • 195
  • 1
  • 2
  • 7

1 Answers1

23
## Example times
x <- c("16:53", "10:57", "11:58")

## POSIX*t objects need both date and time specified
## Here, the particular date doesn't matter -- just that there is one.
tt <- strptime(paste("2001-01-01", x), format="%Y-%m-%d %H:%M")

## Use round.Date to round, then format to format
format(round(tt, units="hours"), format="%H:%M")
# [1] "17:00" "11:00" "12:00"
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
  • you don't really need to add a date, current date will be added automatically if you do `strptime(x, "%H:%M")` – eddi May 08 '13 at 16:33
  • 2
    @eddi -- Cool, but any chance that could get you in trouble for particular times on days with with a daylight savings time shift?? (I *said* the day didn't matter, but for this very reason chose one for which I don't think any place has a DLT shift...) – Josh O'Brien May 08 '13 at 16:36
  • Can't see why it would - and I did just check it and it works normally as far as I can tell. – eddi May 08 '13 at 16:44
  • 2
    @eddi If you're in the US, try setting your computer system date to March 10 2013 (the beginning of our DST this year), and then running `round(strptime("1:31", "%H:%M"), "hours")`. R returns `[1] "2013-03-10 03:00:00 PDT"` -- just what I was wanting to avoid. – Josh O'Brien May 08 '13 at 16:50
  • Thanks Josh! I see why I didn't see a difference before when testing, I was misformating the month by using %M instead of %m. You're right, adding a date is safer. – eddi May 08 '13 at 17:33
  • `round(...)` on a date. aweome - once again proving that we should always be thinking of dates as their underlying numerical structures. thanks @JoshO'Brien! – d8aninja Sep 19 '17 at 14:20