Home > Net >  Given the time in hh:mm:ss format, compute the number of seconds using base R
Given the time in hh:mm:ss format, compute the number of seconds using base R

Time:12-30

I have a character object with the time in hh:mm:ss-like format.

A given vector a for example purposes:

[1] "01|15|59" "1|47|16"  "01|17|20" "1|32|34"  "2|17|17" 

I want to compute the number of seconds for each measurement.

For the first one you can simply do:

a <-  as.numeric(strsplit(a, "|", fixed=TRUE)[[1]])
a[1]*60*60   a[2]*60   a[3]

I could use a loop to iterate through all of the elements of the char object, but ideally I would like to use an apply function. Not sure how to implement it.

CodePudding user response:

You can use sapply():

sapply(strsplit(a, "\\|"), \(x) sum(as.numeric(x) * 60^(2:0)))
# [1] 4559 6436 4640 5554 8237

or convert the time string to POSIXct and pass it to as.numeric() to get seconds:

as.numeric(strptime(paste('1970-01-01', a), '%F %H|%M|%S', 'UTC'))
# [1] 4559 6436 4640 5554 8237
difftime(strptime(a, '%H|%M|%S', 'UTC'), Sys.Date(), units = 'sec')
# Time differences in secs
# [1] 4559 6436 4640 5554 8237

Data
a <- c("01|15|59", "1|47|16", "01|17|20", "1|32|34", "2|17|17")

CodePudding user response:

Note that the | (vertical bar) needs to be escaped in your strsplit(). Otherwise it acts as a logical "or", resulting in a split on each character. Use [|] or \\|.

With a list object created by a <- strsplit(a, '[|]') You as could extract each list element with the `[[` function within sapply(). For example:

#Splits your vector on vertical pipe, with list output
a <- strsplit(a, '[|]')
#Apply extract function across list  
3600*as.numeric( sapply(a,`[[`,1))  
60*as.numeric( sapply(a,`[[`,2)) 
as.numeric( sapply(a,`[[`,3))
[1] 4559 6436 4640 5554 8237
  • Related