我是 R 新手。我的数据有 600k 个对象,由三个属性定义Id
:Date
和TimeOfCall
.
TimeofCall
具有00:00:00
格式和范围从00:00:00
到23:59:59
。
我想将TimeOfCall
属性分箱,分成 24 个箱,每个箱代表每小时时段(第一个箱00:00:00
到00:59:59
等等)。
有人可以告诉我如何做到这一点吗?我尝试使用cut()
但显然我的格式不是数字。提前致谢!
虽然您可以转换为正式的时间表示,但在这种情况下,使用它可能更容易substr
:
test <- c("00:00:01","02:07:01","22:30:15")
as.numeric(substr(test,1,2))
#[1] 0 2 22
使用POSIXct
时间来处理它也可以,如果您计划进一步计算(时间差异等),可能会很方便:
testtime <- as.POSIXct(test,format="%H:%M:%S")
#[1]"2013-12-09 00:00:01 EST" "2013-12-09 02:07:01 EST" "2013-12-09 22:30:15 EST"
as.numeric(format(testtime,"%H"))
#[1] 0 2 22
你可以使用cut.POsixlt
函数。但是您应该将数据强制转换为有效的时间对象。在这里,我正在使用方便hms
的lubridate
. 并strftime
获取时间格式。
library(lubridate)
x <- c("09:10:01", "08:10:02", "08:20:02","06:10:03 ", "Collided at 9:20:04 pm")
x.h <- strftime(cut(as.POSIXct(hms(x),origin=Sys.Date()),'hours'),
format='%H:%M:%S')
data.frame(x,x.h)
x x.h
1 09:10:01 10:00:00
2 08:10:02 09:00:00
3 08:20:02 09:00:00
4 06:10:03 07:00:00
5 Collided at 9:20:04 pm 22:00:00