如何处理时间、距离和速度? [英] How to work with times, distance and speed?

查看:39
本文介绍了如何处理时间、距离和速度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过分析自行车比赛的结果来学习 R,但我在时间数据(一个人完成比赛所需的时间)方面遇到了问题.

I'm learning R by analysing the results of a bike race and I'm having problems with the time data (how much a person took to finish the race).

时间数据的格式为HH:MM:SS".

The time data has the format "HH:MM:SS".

我尝试将其转换为 posixct,但它向其中添加了一个日期组件.我也尝试过 chron 包,但它不会让我用时间对象除以数字

I tried converting it to posixct but it adds a date component to it. I also tried the chron package but it won't let me divide a number by a time object

我想做的一件事是使用这个时间计算平均速度,所以我需要能够除以时间.

One of the things I want to do is to calculate average speeds using this time, so I need to be able to divide distance by time.

推荐答案

您看到的并不是真正的时间,而是经过的时间.有用于经过时间的数据类型.在基础 R 中,difftime 类就是这样做的.

What you are looking at is not really time, but an elapsed time. There are data types for elapsed time. In base R, the difftime class does this.

tms <- c("2:06:00", "3:34:30", "4:12:59", "08:09:10",
         "09:10:11", "10:11:12", "11:12:13")

ta <- as.difftime(tms)

显示为

> ta
Time differences in hours
[1]  2.100000  3.575000  4.216389  8.152778  9.169722 10.186667 11.203611
attr(,"tzone")
[1] ""
> format(ta)
[1] " 2.100000 hours" " 3.575000 hours" " 4.216389 hours" " 8.152778 hours" " 9.169722 hours"
[6] "10.186667 hours" "11.203611 hours"

您也可以通过转换为数字来进行数学计算.

You can do math with this as well by converting to numeric.

> 42.2/as.numeric(ta)
[1] 20.095238 11.804196 10.008564  5.176150  4.602102  4.142670  3.766643

lubridate 包也有处理经过时间的类型,特别是 duration.

The lubridate package also has types that deal with elapsed time, specifically duration.

library("lubridate")
ti <- as.duration(as.difftime(tms))

显示为

> ti
[1] 7560s (~2.1 hours)    12870s (~3.58 hours)  15179s (~4.22 hours)  29350s (~8.15 hours) 
[5] 33011s (~9.17 hours)  36672s (~10.19 hours) 40333s (~11.2 hours) 

并且您可以在转换为数字后使用 is 进行数学运算(此处为秒而不是小时)

and you can do math with is after converting to numeric (here, seconds rather than hours)

> 42.2/as.numeric(ti)
[1] 0.005582011 0.003278943 0.002780157 0.001437819 0.001278362 0.001150742 0.001046290

这篇关于如何处理时间、距离和速度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆