A simple class for storing durations values and displaying them in the Dd HH:MM:SS
format.
Intended to facilitate representation and manipulations of duration in the context of ethological experiments (which typically last several days).
The implementation is exhaustively based on the very neat hms class.
The values are simply stored as a numeric vector a number of seconds. Implicitly, either since the onset of the experiment or since ZT0 on the reference day.
library(devtools) install_github("qgeissmann/dhms") library(dhms)
knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "README-" )
hms
library(dhms) library(hms)
In dhms
, we express number of days to reduce cognitive burden after 72h.
This is convenient for circadian experiments:
seconds <- seq(from =1, to =10 * 24 * 3600, by=27*3600) df <- data.frame(hms=hms(seconds), dhms=dhms(seconds)) print(df)
Parsing optional number of days and negative values:
time_str <- c("12:34:56", # regular format "12:34:56.789", # decimal points "20:12", # HH:MM (no seconds) "-12:34:56.001", # negative values without days "1d 12:34:56", # number of days (integer) "1d 12:34:56.001", # decimal points and days "-1d 12:34:56.001", # negative values "-1d 12:34:56.001", # negative values and space "0.5d" # day only ) df <- data.frame(time_str=time_str, hms=as.hms(time_str), dhms=as.dhms(time_str)) print(df)
In hms
, arithmetic operation return difftime
object
a <- hms(123) # 123 seconds b <- hms(125) print(a - b) # this returns a `difftime` class(a - b) print(a - 1) # this too class(a - 1)
With dhms
, we want to add or subtract constant to our time, but keep expressing the result as a pretty duration. Typically, you want to change the origin of your time, so you just subtract a number of seconds.
a <- dhms(123) b <- dhms(125) print(a - b) # This returns another dhms, which expresses a duration print(class(a - b)) print(a - 1) # Same here print(class(a - 1))
In hms
, we can't compare strings directly to time.
One would have to use as.hms()
on strings before comparison, which explicitly converts them to hms
objects.
It is quite convenient to compare formatted strings directly to objects.
This is what happens in R for things like POSIXct
objects:
date = as.POSIXct("2017-12-12") print(date) print(date == "2017-12-12") print(date > "2015-06-12" )
Likewise, in dhms
, operations with strings implicitly converts to a duration representation.
time_str <- "00:02:10" a_hms <- as.hms(time_str) b_hms <- as.hms("00:02:02") a_dhms <- as.dhms(time_str) b_dhms <- as.dhms("00:02:02") dt <- data.frame(operation = c("a == 00:02:10", "b > a", "b > 00:02:10", "a + 00:02:10"), hms=c(a_hms == time_str, b_hms > a_hms, b_hms > time_str, "FAILS"), dhms=c(a_dhms == time_str, b_dhms > a_dhms, b_dhms > time_str, as.character(a_dhms + time_str)) ) print(dt)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.