[R] Round down to earliest hour or half hour

Phil Hurvitz phurvitz at uw.edu
Sat Jun 9 04:04:35 CEST 2012


I wanted to round rather than truncate timestamps

# create a data set to work with
s <- 30 * rnorm(10, 1, 0.1)
gps.timestamp <- Sys.time() + s*1:10
gps.timestamp <- c(round(gps.timestamp[1], "min"), gps.timestamp, 
as.POSIXct("2012-06-08 17:32:59"), as.POSIXct("2012-06-08 17:32:30"))

f <- function(gps.timestamp=gps.timestamp, interval=30){
     # is the interval a multiple of 60? if so, just round
     if(interval %% 60 == 0){
         return(data.frame(gps.timestamp, 
gps.timestamp.round=round(gps.timestamp, "min")))
     }
     # a POSIXlt timestamp for fiddling with seconds
     lt <- as.POSIXlt(gps.timestamp)
     # extract rounded seconds from the timestamp
     gps.seconds <- round(lt$sec, 0)
     # the number of segments in a minute is 60/interval
     seg <- 60/interval
     # the cutpoints
     rounds <- c(0, 1:seg * interval)
     # the "midpoints" for cutting
     cuts <- c(-1, 1:seg * 60/seg - interval/2, 60)
     # and a numeric representation of the cut position
         # (the factor position, really)
     numcut <- as.numeric(cut(gps.seconds,cuts))
     # the rounded seconds (*not* truncated)
     round.seconds <- rounds[numcut]
     # truncate the date to the nearest low minute
     lt <- lt1 <- trunc(lt, "min")
     # add the rounded seconds to the truncated minutes
     lt1 <- lt1 + round.seconds
     # how does that look?
     return(data.frame(gps.timestamp, gps.timestamp.round=lt1))
}


# try it:
f(gps.timestamp, 15)
f(gps.timestamp, 30)
f(gps.timestamp, 10)

-P.

**************************************************************
Philip M. Hurvitz, PhD | Research Assistant Professor | UW-CBE
Urban Form Lab  | 1107 NE 45th Street, Suite 535  | Box 354802
University of Washington, Seattle, Washington  98195-4802, USA
phurvitz at u.washington.edu | http://gis.washington.edu/phurvitz
"What is essential is invisible to the eye." -de Saint-Exupéry
**************************************************************

> I would use package chron and trunc()....
>
> One example from the help of trunc.times (modified):
>
> lirary(chron)
> tt <- times(c("12:13:14", "15:46:17"))
> trunc(tt, times("00:30:00"))
>
>
> HTH
> Jannis
>
> --- Schatzi <adele_thompson at cargill.com> schrieb am Mo, 9.5.2011:
>
>> Von: Schatzi <adele_thompson at cargill.com>
>> Betreff: [R] Round down to earliest hour or half hour
>> An: r-help at r-project.org
>> Datum: Montag, 9. Mai, 2011 14:06 Uhr
>> I have times and would like to round
>> down to the earliest 30 minute
>> increment. For instance, a time of
>> 2011-04-28 09:02:00
>> (the as.numeric value = 1303999320)
>> I would like it to be rounded down to:
>> 2011-04-28 09:00:00
>> (the as.numeric value = 1303999200)
>>
>> Any ideas of how to do this?



More information about the R-help mailing list