Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rounding times to the nearest hour in R [duplicate]

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?

like image 894
user1558387 Avatar asked May 08 '13 15:05

user1558387


People also ask

How to round time in R?

Description. round_date() takes a date-time object and time unit, and rounds it to the nearest value of the specified time unit. For rounding date-times which are exactly halfway between two consecutive units, the convention is to round up. Note that this is in line with the behavior of R's base::round.

How do you round to the nearest hour?

When reporting time not worked, employees should round to the nearest 1/4 hour. For example: 15 minutes = 0.25 hours, 30 minutes = 0.50 hours and 45 minutes = 0.75 hours. Examples: The employee leaves early due to illness 1 hour and 45 minutes before the end of the day.

How do you round date and time?

Rounding Up Date Objects Round up to the next closest rounding unit boundary. For example, if the rounding unit is month then next closest boundary of 2000-01-01 is 2000-02-01 00:00:00 .


1 Answers

## 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"
like image 66
Josh O'Brien Avatar answered Oct 04 '22 00:10

Josh O'Brien