R中比较小时
问题描述:
这里是我的样本数据集R中比较小时
id hour
1 15:10
2 12:10
3 22:10
4 06:30
我需要找到的最早时间和最晚时间。 hour
的等级是因素。所以我需要将因素转换为合适的班级,并比较早期和晚期时间。我试着用下面的代码格式化hour
,但它并没有chron
包的工作,如预期
format(as.Date(date),"%H:%M")
答
使用times
#Data
xx
# id hour
#1 1 15:10
#2 2 12:10
#3 3 22:10
#4 4 06:30
library(chron)
xx$hour = times(paste0(as.character(xx$hour), ":00"))
xx
# id hour
#1 1 15:10:00
#2 2 12:10:00
#3 3 22:10:00
#4 4 06:30:00
#Min and Max
range(xx$hour)
#[1] 06:30:00 22:10:00
xx = structure(list(id = 1:4, hour = structure(c(3L, 2L, 4L, 1L), .Label = c("06:30",
"12:10", "15:10", "22:10"), class = "factor")), .Names = c("id",
"hour"), row.names = c(NA, -4L), class = "data.frame")
答
如果你需要的是查找最早(最短)和最近(最长)次,您可以将时间转换为字符并使用min
,max
:例如,
hour <- c("15:10", "12:10", "22:10", "06:30")
hour[which(hour == max(hour))]
> "22:10"