0

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?

amonsie
  • 15
  • 4
  • Please paste in your data using results of `dput(mydata column)`. – Eric Krantz Nov 24 '20 at 15:41
  • Does this answer your question? [R: Convert hours:minutes:seconds](https://stackoverflow.com/questions/29067375/r-convert-hoursminutesseconds) – Clemsang Nov 24 '20 at 15:43
  • What do you mean with a numeric hour value? Do you mean that 0:00:00 becomes 0.0, 0:10:00 becomes 0.1, and 1:10:00 becomes 1.1? – MacOS Nov 24 '20 at 15:43

2 Answers2

1

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)

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
1

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")
akrun
  • 874,273
  • 37
  • 540
  • 662