Round time values to a specified minute interval


Problem


You want to round time values to some specified minute interval.

 


Solution


Use this custom function to round time values to some specified minute interval.

Arguments for this function:

  • x:  a date-time object class
  • y:  a numeric value for the minute interval you would like to round to.  Note, y must be between 0-60; set y=60 to round to hours.

 

# Create example data
t.input<- as.POSIXct(c("2013-11-25 12:56:15", "2013-11-25 12:43:02", "2013-11-25 12:36:38",
                 "2013-11-25 12:22:50", "2013-11-25 12:02:07"))
t.input
 
# Define the custom function
roundMin<- function(x, y){ 
  #first test for the correct data type
  if(!inherits(x, "POSIXct")){
    if(!inherits(x, "POSIXlt")){
      stop("object(x): Class is not POSIXct or POSIXlt")
    }
  }
  if(!is.numeric(y)){
    stop("object(y): Value is not numeric")
  }
  if(y<0){
    stop("object(y): Value is out of range. Must be between 0 and 60")
  }
  if(y>60){
    stop("object(y): Value is out of range. Must be between 0 and 60")
  }
  if(y==0){
    #set y equal to top of hour
    y<-60
  }
  #create a threshold of half of the minute interval to round up or down from 
  x<- as.POSIXlt(x + as.difftime((y/2), units="mins")) 
  #Set seconds to zero because we are rounding the minutes 
  x$sec<- 0 
  # divide by the remainder of the quotient, then multiply the interval to that answer
  x$min<- y*(x$min %/% y)
  #convert the rounded time to POSIXct  
  as.POSIXct(x)  
}#close function
 
# Employ function using different example rounding times
roundMin(t.input, 60) #round to nearest hour
roundMin(t.input, 30) #round to nearest 30 min. 
roundMin(t.input, 5) #round to nearest 5 min.

 


Notes


Dylan Perkins contributed to the development of this tool.