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?
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?
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
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 r
You are not signed in. Login or sign up in order to post.
One can use
sapply
instead ofunlist/lapply
, since the first by default simplifies the output by returning a vector.– Rui Barradas
Thanks for the tip!
– Marcus Nunes
Thank you very much! that’s exactly what I was prejudging
– Luciano Hauschild
@Marcusnunes A similar question was asked today in ONLY in English.
– Rui Barradas
How nice to know I helped more people :-)
– Marcus Nunes
@Lucianohauschild, how good that the answer helped you! It would be possible to accept it so that more people with the same doubt could be helped in the future? https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta this link shows how and why to do this.
– Marcus Nunes