Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R: how to divide period by integer in lubridate?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# 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".

>Solution :

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)"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading