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:
(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?)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With