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

Asked

Viewed 1,908 times

3

I am trying to convert a column in the date.frame that is in the format of hour:minutes: second to decimal number Example: 2:20:00 to 2,33

How can I do it in R?

2 answers

3


Since I don’t have access to your original dataset, I’m going to assume that the time is not in date format, but in character, like "h:m:s".

I created the function HoraDecimal, that 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))
}

Here’s what she does:

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

  • 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 into a vector

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

  • Finally, sum makes the sum and organizes the final result

See the function HoraDecimal 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
Show 1 more comment

0

you can use the lubridate to install

install.packages("lubridate")

to load the library

library("lubridate")

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

y <- hms(x)
hour(y) + minute(y) / 60 + second(y) / 360

Browser other questions tagged

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