I am searching all over help for R function that would convert timespan, for example "15 min" or "1 hour" or "6 sec" or "1 day" into datetime object like "00:15:00" or "01:00:00" or "00:00:06" or "1960-01-02 00:00:00" (not sure for this one). I am sure a function like this exists or there is a neat way to avoid programming it...
To be more specific I would like to do something like this (using made up function name transform.span.to.time):
library(chron)
times(transform.span.to.time("15 min"))
which should yield the same result as
times("00:15:00")
Does a function like transform.span.to.time("15 min") which returns something like "00:15:00" exists or does there exists a trick how to do that?
We will assume a single space separating the numbers and units, and also no trailing space after "secs" unit. This will handle mixed units:
@DWin: thank you.
Based on DWin example I rearranged a bit and here is the result:
You can define the time span with
difftime
:For example:
EDIT: modified to produce character string acceptable to chron's
times
.The first solution uses
strapply
in the gsubfn package and transforms to days, e.g. 1 hour is 1/24th of a day. The second solution transforms to an R expression which calculates the number of days and then evaluates it.Here is a second solution:
Tests:
The base function
?cut.POSIXt
does this work for a specified set of values forbreaks
:See the source code by typing in
cut.POSIXt
, the relevant section starts with this:You could adopt the code in this section to work for your needs.