Time formatting

Hope everyone is having a nice Thanksgiving. I'm having a bit of trouble formatting times in my data frame, in such a way that they are usable. They are currently formatted as follows: 9m2.75s, which indicates 9 minutes and 2.75 seconds.

This indicates the number of minutes and seconds. I am trying to parse it in such a way that it can be read into a plot as a time. Any ideas on this would be useful. I've been stuck on it for a while.

This will get you a date time object from strings with that format, and from there you can pick the components for plot

library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date
exemplar <- "9m2.75s"
parse_date_time(exemplar, "MS")
#> [1] "0000-01-01 00:09:03 UTC"

Created on 2019-11-28 by the reprex package (v0.3.0)

This worked! Thank you!!

1 Like

Great, glad that worked. For the benefit of those who follow, please mark this as a solution to make it easier to find. In the words of the old song

penny a point, ain't no one keepin' score

1 Like

A brief follow up to this. Any ideas on how to convert to a "duration"? In other words, instead of 00:01:30, I just want this to be 90.

1 Like

On second thought, going down the rabbit hole into date time may not be the best way to end up with a number of seconds if, indeed, you're dealing solely with "9m2.75s" that you want to convert to integers.

Here is a clunky example of taking this as a string parsing and conversion problem. Needs adjustment, obviously, if fractional seconds are not guaranteed in the input.

library(stringr)
get_secs <- function(x) {
    pattern <- "\\d+"
    str_extract_all(x, pattern)
}

make_secs <- function(x) {
     big_secs <- as.integer(x[[1]][1]) * 60
     reg_secs <- as.integer(x[[1]][2])
     frac_secs <- ifelse(as.integer(x[[1]][3]) > 49, 1, 0)
     tot_secs <- big_secs + reg_secs + frac_secs
}

exemplar <- "9m2.75s"
sec_chars <- get_secs(exemplar)
result <- get_secs(exemplar) %>% make_secs()
result
#> [1] 543

Created on 2019-11-28 by the reprex package (v0.3.0)

You can get a more flexible function with regular expressions

library(stringr)

get_seconds <- function(x) {
    res <- as.numeric(str_match(x, "(\\d+).(\\d{1,2}\\.?\\d{0,2}).")[2:3])
    res[1]*60+res[2]
}

get_seconds("9m2.75s")
#> [1] 542.75
round(get_seconds("9m2.75s"))
#> [1] 543
get_seconds("12m2s")
#> [1] 722
2 Likes