How to turn hours into seconds in R?

Asked

Viewed 1,025 times

7

I have the following schedules:

2:00:00 3:00:00 6:00:00 4:00:00 4:00:00 3:00:48 1:00:00 3: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 3:00 3:00:00:48 4:00:00 4:30:00

How to turn all this in seconds?
I’ve tried so many ways and I can’t.

1 answer

5


1 hour equals 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"

We’re gonna use Split. Multiply the first number by 3600 and the second by 60 and the last by 1. And add them to each other, 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 meianoite[seconds]):

as.numeric(strptime(x, format="%H:%M:%S") - as.POSIXct(format(Sys.Date())), units="secs")
  • Thank you very much!!!! You know how I can put this in a new variable and add it to my database ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.