Binning time data in R

后端 未结 1 604
情话喂你
情话喂你 2020-12-11 13:08

I have time data for departures and arrivals of birds (e.g. arrival 17:23:54). I would like to bin the data into 2 hour time bins (e.g. 0:00:00-1:59:59...etc), so 12 total b

相关标签:
1条回答
  • 2020-12-11 13:40

    Just use ?cut as it has a method for ?cut.POSIXt date/times. E.g.:

    x <- as.POSIXct("2016-01-01 00:00:00", tz="UTC") + as.difftime(30*(0:47),units="mins")
    cut(x, breaks="2 hours", labels=FALSE)
    # or to show more clearly the results:
    data.frame(x, cuts = cut(x, breaks="2 hours", labels=FALSE))
    
    #                     x cuts
    #1  2016-01-01 00:00:00    1
    #2  2016-01-01 00:30:00    1
    #3  2016-01-01 01:00:00    1
    #4  2016-01-01 01:30:00    1
    #5  2016-01-01 02:00:00    2
    #6  2016-01-01 02:30:00    2
    #7  2016-01-01 03:00:00    2
    #8  2016-01-01 03:30:00    2
    #9  2016-01-01 04:00:00    3
    #10 2016-01-01 04:30:00    3
    # ...
    

    If your data are just strings, then you need to do a conversion first. Times will end up assigned to the current day if you don't specify a particular day as well.

    as.POSIXct("17:23:54", format="%H:%M:%S", tz="UTC")
    #[1] "2016-07-13 17:23:54 UTC"
    
    0 讨论(0)
提交回复
热议问题