Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From timespan (for example "15 min" or "2 sec") to "00:15:00" or "00:00:02"

Tags:

r

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?

like image 535
Samo Avatar asked Nov 20 '11 21:11

Samo


1 Answers

We will assume a single space separating the numbers and units, and also no trailing space after "secs" unit. This will handle mixed units:

test <- "0 hours 15 min 0 secs"

 transform.span <- function(test){ 
     testh <-         if(!grepl( " hour | hours ", "0 hours 15 min 0 secs")){ 
             # First consequent if no hours
                                      sub("^", "0:", test)} else { 
                                      sub(" hour | hours ", ":", test)}
     testm <- if(!grepl( " min | minutes ", testh)) {    
             #  first consequent if no minutes
                                      sub(" min | minutes ", "0:", testh)} else{
                                      sub(" min | minutes ", ":", testh)  }

     test.s <- if(!grepl( " sec| secs| seconds", testm)) { 
              # first consequent if no seconds
                                       sub(" sec| secs| seconds", "0", testm)} else{ 
                                       sub(" sec| secs| seconds", "", testm)}

     return(times(test.s)) }
###  Use
> transform.span(test)
[1] 00:15:00
> test2 <- "21 hours 15 min 38 secs"
> transform.span(test2)
[1] 21:15:38
like image 192
IRTFM Avatar answered Oct 05 '22 11:10

IRTFM