How to turn hours in seconds in R?

6

I have the following times:

  

2:00:00 3:00:00 6:00:00 4:00:00 4:00:00 3:00:48 1:00:00 3:00:00 2:00:00 4: 00:00 1:30:00
   2:00:00 1:00:00 3:00:00 4:00:00 4:30:00 5:00:00 1:00:00 1:30:00 2:00:00 3:00:00 3:00:48    4:00:00 4:30:00

How to turn all this into seconds?
I've tried it in several ways and I can not.

    
asked by anonymous 06.10.2014 / 02:21

1 answer

3

1 hour is equal to 3600 seconds ... then ...

# Vamos ler os dados
x <- unlist(strsplit("2:00:00 3:00:00 6:00:00 4:00:00 4:00:00 3:00:48 1:00:00 3:00:00 2:00:00 4:00:00 1:30:00 2:00:00 1:00:00 3:00:00 4:00:00 4:30:00 5:00:00 1:00:00 1:30:00 2:00:00 3:00:00 3:00:48 4:00:00 4:30:00", "[[:space:]]+"))
x
# [1] "2:00:00" "3:00:00" "6:00:00" "4:00:00" "4:00:00" "3:00:48" "1:00:00"
# [8] "3:00:00" "2:00:00" "4:00:00" "1:30:00" "2:00:00" "1:00:00" "3:00:00"
#[15] "4:00:00" "4:30:00" "5:00:00" "1:00:00" "1:30:00" "2:00:00" "3:00:00"
#[22] "3:00:48" "4:00:00" "4:30:00"

Let's use Split. Multiply the first number by 3600 and the second by 60 and the last by 1. And add them together, we can use a matrix multiplication for this.

sapply(strsplit(x, ":"), function(n) as.numeric(n) %*% c(3600, 60, 1))

Another alternative using POSIXct (subtracting midnight [seconds]):

as.numeric(strptime(x, format="%H:%M:%S") - as.POSIXct(format(Sys.Date())), units="secs")
    
06.10.2014 / 04:50