0

我在向量中有一系列时间值:

# 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

所以问题是:是否有一种简单、干净的方法来处理时间值来执行此操作和类似的计算?

4

1 回答 1

0

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
于 2013-11-02T02:07:34.607 回答