Lubridate makes working with time easier, but sometimes it is hard for me to understand.
What I would like to do is to divide a period by integer. For example:
If I run 5 km in 24m:45s what would I run 1 km in?
# period gives me a time object
> as.period(ms("24:30"))
[1] "24M 30S"
But if I try to divide by 5 to get another object in minutes and seconds, it throws an error.
> as.period(ms("24:30"))/5
Error in validObject(.Object) :
invalid class “Period” object: periods must have integer values
What is the cause of this error and how to overcome this?
Many thanks:
Based on answer and comment below this is the solution:
> as.period(as.duration(ms("24:30"))/5)
[1] "4M 54S"
It is necessary due to imprecise nature of period - "periods do not have fixed length".
CodePudding user response:
I recommend the Duration
class over the Period
class for your use case (running time).
The exact length of each time unit in a period will depend on when it occurs. See Period and period(). [...]
Because periods do not have a fixed length, they can not be accurately converted to and from Duration objects. Duration objects measure time spans in exact numbers of seconds
as.duration(ms("24:30")) / 5
#> [1] "294s (~4.9 minutes)"