Reputation: 7404
I have some time data
01:09:00
00:14:00
00:00:00
11:47:00
10:34:00
08:15:00
The data are measured in %M:%S:00
(to the first numbers are the minutes, the second numbers are the seconds). I would like to convert this into a total number of seconds. This is easy to do with lubridate
but R keeps thinking the format is in %H:%M:%S
.
Can lubridate calculate the total number of seconds elapsed in the format my data are in? If not, how is the best way to transform the data into an appropriate format?
I've thought about converting to character and just splicing out the minutes and seconds.
Upvotes: 0
Views: 365
Reputation: 67778
You may use data.table::as.ITime
and specify format as "%M:%S"
*:
x <- c("01:09:00", "10:34:00")
as.integer(as.ITime(x, format = "%M:%S"))
# [1] 69 634
*The format
argument is passed to strptime
and...
Each input string is processed as far as necessary for the format specified: any trailing characters are ignored. [...] Note that
%S
does not read fractional parts on output.
Or, most likely faster, substr
:
as.integer(substr(x, 1, 2)) * 60 + as.integer(substr(x, 4, 5))
# [1] 69 634
Upvotes: 0
Reputation: 76402
Maybe the following will do it.
NumSeconds <- function(x){
f <- function(y)
sum(sapply(strsplit(y, split=":"), as.numeric) * c(60, 1, 0))
unname(sapply(x, f))
}
x <- scan(what = "character", text = "
01:09:00
00:14:00
00:00:00
11:47:00
10:34:00
08:15:00")
NumSeconds(x)
[1] 69 14 0 707 634 495
Upvotes: 0
Reputation: 32548
library(lubridate)
foo = function(x){
hms(sapply(strsplit(x, ":"), function(xx) paste("01", xx[1], xx[2], sep = ":")))
}
a = "01:09:00"
b = "00:14:00"
foo(a) - foo(b)
#[1] "1M -5S"
#OR
as.period(foo(a) - foo(b), unit = "secs")
#[1] "55S"
Upvotes: 1