Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculations with minutes and seconds in R

I'm new to the R statistics software and I roast coffee and record different events during the process. After the roasting process I would like to use R to do some calculation and analysis and derive important durations during the period by finding the time span between events - for example:

  • 00:00 Start
  • 05:10 Yellow
  • 07:15 Cinnamon
  • 09:00 First Crack
  • 11:30 End of roasting process

(if you are a coffee geek and want to know more about coffee roasting parameters: https://coffee-mind.com/profile/)

How/what format can I store these events and calculate the time span between events? I would like to show the time span in MM:SS but also see the total seconds in a MM:SS period. I have been looking at the different packages (like chron and lubridate) but they all seem to be concerned with time zone, absolute dates and so on and I'm only interested in minutes and seconds (regardless of day and time zone - not interesting at all here) and how to do calculations like simple subtractions on these recorded events. I'm not interested in 'how to write the code' but in functions (like chron and lubridate) that are already designed for this and how to use them directly (which I also assume is the most generally interesting approach for this community?)

like image 354
Morten Münchow Avatar asked Mar 13 '23 04:03

Morten Münchow


1 Answers

lubridate offers the functionality that you need. In addition to the POSIXct class, which does include date and time, it also offers the class period for durations. You can convert your times in %M:%S format to period as follows:

library(lubridate)
times <- c("00:00", "05:10", "07:15", "09:00", "11:30")
ms(times)
## [1] "0S"      "5M 10S"  "7M 15S"  "9M 0S"   "11M 30S"

You can then use as.period() to convert to the time unit you desire:

as.period(ms(times), unit = "sec")
## [1] "0S"   "310S" "435S" "540S" "690S"

If you convert to numeric now, you will get the seconds as numbers:

seconds <- as.numeric(as.period(ms(times), unit = "sec"))
seconds
## [1]   0 310 435 540 690

You can get now the difference in seconds between the events using diff() :

diff(seconds)
##[1] 310 125 105 150

Note that there are other variants of the function ms() for times in other formats: hm() (%H:%M:%S) and hms() (%H:%M).

like image 184
Stibu Avatar answered Mar 14 '23 16:03

Stibu