在R中分箱时间数据

Cru*_*ruz 0 time r binning

我有离开和到达鸟类的时间数据(例如到达17:23:54).我想将数据分成2小时的时间段(例如0:00:00-1:59:59 ......等),共12个箱.数据最终将进入条形图,其中x轴上有时间段,y轴上有计数.包裹'binr'会是我最好的选择吗?

谢谢

the*_*ail 5

只需使用,?cut因为它有一个?cut.POSIXt日期/时间的方法.例如:

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
# ...
Run Code Online (Sandbox Code Playgroud)

如果您的数据只是字符串,那么您需要先进行转换.如果您未指定特定日期,则时间将最终分配到当天.

as.POSIXct("17:23:54", format="%H:%M:%S", tz="UTC")
#[1] "2016-07-13 17:23:54 UTC"
Run Code Online (Sandbox Code Playgroud)