How to convert Hour: minutes: seconds to decimal number in R

2

I am trying to convert a column in the data.frame that is in the format of hour: minutes: second to decimal number Example: 2:20 PM to 2.33

How can I do this in R?

    
asked by anonymous 18.08.2017 / 11:18

2 answers

2

As I do not have access to your original dataset, I'll assume that the times are not in date format, but rather character, type "h: m: s".

I created the HoraDecimal function, which does exactly what you need. See it below:

HoraDecimal <- function(x){
  sum(unlist(lapply(strsplit(x, split=":"), as.numeric)) * c(1, 1/60, 1/3600))
}

It does the following:

  • The function strsplit separates the original string according to the ":". Therefore, every entry in this function must be in the format h: m: s, even if it is 0 hours.

  • lapply , combined with as.numeric , serves to transform the characters obtained with the previous function into numbers

  • unlist makes the list created by lapply turn a vector

  • When multiplying this vector by c(1, 1/60, 1/3600) , I get the values that interest me in fractions of time

  • Finally, sum sums and organizes the final result

See the HoraDecimal function applied to time data in the format "h: m: s":

x <-  "02:20:00"
HoraDecimal(x)
[1] 2.333333

y <-  "00:50:00"
HoraDecimal(y)
[1] 0.8333333

z <- "3:30:30"
HoraDecimal(z)
[1] 3.508333
    
18.08.2017 / 12:48
0

you can use lubridate to install

install.packages("lubridate")

to load the library

library("lubridate")

first converting your string to a time format and then converting it to a decimal

y <- hms(x)
hour(y) + minute(y) / 60 + second(y) / 360
    
31.08.2017 / 00:48