我在向量中有一系列时间值:
# Source data in %m:%s"
>intervals <- c("1:30", "1:33", "1:29", "1:31", "1:30")
如果我想对这些值取平均值,则可以使用以下strptime()
函数:
# Averaging with strptime()
> meantime <- mean(strptime(intervals,"%M:%S"))
> meantime
[1] "2013-11-01 00:01:30 PDT"
但我不需要日期和时区的内容。当我想用该时间值做进一步的计算时,我遇到了问题。假设这些时间值属于一条400 m长的赛道。让我们计算平均速度和速度:
> distance <- as.numeric(400)
> distance
[1] 400
> # Let's calculate the average speed:
> distance/meantime
Error in Ops.POSIXt(distance, meantime) :
'/' not defined for "POSIXt" objects
> # Let's calculate the average pace:
> meantime / distance
Error in Ops.POSIXt(meantime, distance) :
'/' not defined for "POSIXt" objects
那么问题来了:是否存在一种简单,干净的方法来处理时间值以进行此操作和类似的计算?
difftime函数将返回日期时间值的差异(以秒为单位,相对于GMT):
inters <- strptime(intervals,"%M:%S")
inters
difftime( inters , Sys.Date())
Time differences in hours
[1] 7.025000 7.025833 7.024722 7.025278 7.025000
attr(,"tzone")
[1] ""
# I appear to be 7 hours off from GMT here on the Left Coast of the US.
因此,这并非我们所希望的那么容易,因此请看一下as.difftime
函数:
intervals <- c("1:30", "1:33", "1:29", "1:31", "1:30")
inters <- as.difftime(intervals,"%M:%S")
inters
#
Time differences in mins
[1] 1.500000 1.550000 1.483333 1.516667 1.500000
attr(,"tzone")
[1] ""
distance=400
> as.numeric(inters)/ distance
[1] 0.003750000 0.003875000 0.003708333 0.003791667 0.003750000
# Remembering that these are in minutes
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句