Binning time data in R

2019-01-27 09:04发布

问题:

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 bins. The data would eventually go into a bar graph with time bins on the x axis and count on the y axis. Would package package ‘binr’ be my best bet?

Thanks

回答1:

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"


标签: r time binning