Is there a way to convert mm:ss.00 to seconds.00? Is there a way to convert mm:ss.00 to seconds.00? r r

Is there a way to convert mm:ss.00 to seconds.00?


Using lubridate package (part of tidyverse):

library(lubridate)period_to_seconds(hms("12:12:54"))


Here's one I've used for a number of years. It's vectorized, too.

toSeconds <- function(x){   if (!is.character(x)) stop("x must be a character string of the form H:M:S")   if (length(x)<=0)return(x)   unlist(      lapply(x,         function(i){            i <- as.numeric(strsplit(i,':',fixed=TRUE)[[1]])            if (length(i) == 3)                i[1]*3600 + i[2]*60 + i[3]            else if (length(i) == 2)                i[1]*60 + i[2]            else if (length(i) == 1)                i[1]         }        )     )  } 

And the reverse (preserves fractional seconds to the number of digits requested:

secondsToString <- function(x,digits=2){   unlist(      lapply(x,         function(i){            # fractional seconds            fs <- as.integer(round((i - round(i))*(10^digits)))            fmt <- ''            if (i >= 3600)               fmt <- '%H:%M:%S'            else if (i >= 60)            fmt <- '%M:%S'            else               fmt <- '%OS'            i <- format(as.POSIXct(strptime("0:0:0","%H:%M:%S")) + i, format=fmt)            if (fs > 0)               sub('[0]+$','',paste(i,fs,sep='.'))            else               i         }      )   )}


Look into strptime. Specifically

t = "02:15.45"(as.numeric(as.POSIXct(strptime(t, format = "%M:%OS"))) -     as.numeric(as.POSIXct(strptime("0", format = "%S"))))

This will work, but is possibly a little awkward (doing it this way mostly because of POSIXct's annoying automatic unit conversion...)