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

I have runtime data in the format mm: ss.00 (i.e. 02: 15.45 or 00: 34.58). R recognizes the variable as a factor, but I would like to convert each runtime to a few seconds (i.e. 02: 15.45 - 135.45). I was looking for an answer, but cannot find a way to make it work. Thanks in advance.

+15
time r
source share
6 answers

Using the lubridate package (part of tidyverse):

library(lubridate) period_to_seconds(hms("12:12:54")) 
+21
source share

Here I used a few years. It is also vectorized.

 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 vice versa (saves fractional seconds by the number of requested digits:

 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 } ) ) } 
+16
source share

Take a look at 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 maybe a little inconvenient (this is mainly due to POSIXct, which annoys automatic unit conversion ...)

+8
source share
 library(lubridate) df$variable<- hms(df$variable) df$variable<- as.numeric(df$variable) 

make it one liner. Works like a charm to me.
Hope this helps.

+4
source share

It’s not very convenient for me, so I don’t know if there is a built-in function, but I developed this code.

 mmss_to_ss <- function (string) { mmss <- strsplit (string, ":", T) mm <- as.numeric (mmss[[1]][1]) ss <- as.numeric (mmss[[1]][2]) return (mm * 60 + ss) } 

This will take a temporary string in the format mm: ss and return a second value. The code can be easily modified to convert from hh: mm: ss to seconds.

+3
source share

You can do this easily with the Lubridate package. If you use the format "h: m: s", you can convert the variable to a lubridate object with

 hms("12:12:54") 

And then convert it in seconds with

 seconds(hms("12:12:54")) 

Here is the link to the lubridate article in JSS

http://www.jstatsoft.org/v40/i03/paper

0
source share

All Articles