R中的分箱时间数据 [英] Binning time data in R
问题描述
我有鸟类出发和到达的时间数据(例如,到达时间为 17:23:54).我想将数据分成 2 小时的时间段(例如 0:00:00-1:59:59...等),所以总共有 12 个时间段.数据最终会进入一个条形图,在 x 轴上有时间段,在 y 轴上计数.包包‘binr’是我最好的选择吗?
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?
谢谢
推荐答案
只需使用 ?cut
因为它有一个用于 ?cut.POSIXt
日期/时间的方法.例如:
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中的分箱时间数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!