Home > Software design >  Converting lap times from weird format to seconds only
Converting lap times from weird format to seconds only

Time:11-09

In the dataset "Australian Grand Prix" I can't figure out how to turn the "time" variable column from the (character) format "1M 43.702S" to just seconds in the format "103.702" as a numeric.

edit: The "1M 43.702s" is just the first time in the column, what is the best way for converting the whole column?

Does anyone know a nice way of doing this?

CodePudding user response:

For a base R option, we can use sub to extract the minute and second components as strings, cast them to numeric, and take the sum:

x <- "1M 43.702S"
m <- 60*as.numeric(sub("^(\\d (?:\\.\\d )?)M.*$", "\\1", x))
s <- as.numeric(sub("^.*(?<!\\S)(\\d (?:\\.\\d )?)S$", "\\1", x, perl=TRUE))
output <- m   s
output

[1] 103.702

CodePudding user response:

Using lubridate

time_str = "1M 43.702S"     
lubridate::seconds(lubridate::ms(time_str))
    [1] "103.702S"

If you need it as a numeric (suggestion by @Allan Cameron):

 as.numeric(lubridate::seconds(lubridate::ms(time_str)))
[1] 103.702
  • Related