I have this vector
time = c("2m 14,8s", "1h 47m 46,9s", "34,7s")
And I would like to get this (convert time to secs)
time = c(134.8, 6466.9, 34.7)
I try lapply that split my string and find character that indicates hours or minutes
lapply(str_split(sub(",", ".", time), " "), function(x)
ifelse(grepl("h", x), sub("[a-z]", "", x) * 120,
ifelse(grepl("m", x), sub("[a-z]", "", x) * 60, NULL)))
but this error occurs
non-numeric argument to binary operator
and my second problem is that I don't know how to sum output
You need to replace ','
with '.'
and convert the abbreviations of hours, minutes, and seconds to upper-case characters so that as.duration()
from lubridate
can recognize and change them to a duration.
library(lubridate)
as.numeric(as.duration(toupper(sub(',', '.', time))), "seconds")
# [1] 134.8 6466.9 34.7