Reputation: 15
I currently have a column of time in HH:MM:SS format and need to convert it to a numeric hour value
[1] "0:00:00" "0:10:00" "0:20:00" "0:30:00" "0:40:00"
[6] "0:50:00" "1:00:00" "1:10:00" "1:20:00" "1:30:00"
[11] "1:40:00" "1:50:00" "2:00:00" "2:10:00" "2:20:00"
I was going to use the program lubridate
but is there a more efficient way to do this?
Upvotes: 0
Views: 113
Reputation: 887851
An option with lubridate
is
library(lubridate)
period_to_seconds(hms(vec))/3600
#[1] 0.0000000 0.1666667 0.3333333 0.5000000 0.6666667 0.8333333 1.0000000 1.1666667 1.3333333 1.5000000 1.6666667 1.8333333 2.0000000
#[14] 2.1666667 2.3333333
data
vec <- c("0:00:00", "0:10:00", "0:20:00", "0:30:00", "0:40:00", "0:50:00",
"1:00:00", "1:10:00", "1:20:00", "1:30:00", "1:40:00", "1:50:00",
"2:00:00", "2:10:00", "2:20:00")
Upvotes: 1
Reputation: 174478
You can do:
sapply(strsplit(vec, ":"), function(x) {
x <- as.numeric(x)
x[1] + x[2]/60 + x[3]/3600 })
#> [1] 0.0000000 0.1666667 0.3333333 0.5000000 0.6666667 0.8333333 1.0000000
#> [8] 1.1666667 1.3333333 1.5000000 1.6666667 1.8333333 2.0000000 2.1666667
#> [15] 2.3333333
Data
vec <- c("0:00:00", "0:10:00", "0:20:00", "0:30:00", "0:40:00", "0:50:00",
"1:00:00", "1:10:00", "1:20:00", "1:30:00", "1:40:00", "1:50:00",
"2:00:00", "2:10:00", "2:20:00")
vec
#> [1] "0:00:00" "0:10:00" "0:20:00" "0:30:00" "0:40:00" "0:50:00" "1:00:00"
#> [8] "1:10:00" "1:20:00" "1:30:00" "1:40:00" "1:50:00" "2:00:00" "2:10:00"
#> [15] "2:20:00"
Created on 2020-11-24 by the reprex package (v0.3.0)
Upvotes: 1