I have a data set with a variable for hours in a decimal format (see example df).
I need to convert it to time format (see example df2)
I am trying with lubridate but it gives me wrong values. Do you know how could I easily do it?
Thank you so much in advance
df <- as.data.frame(c(9.5, 9.75, 9, 9.25))
df2 <- as.data.frame(c("9:30", "9:45", "9" , "9:15"))
1
You could handle this in a custom function like the one below:
parse_date <- function(numeric_date) {
hours <- floor(numeric_date)
minutes <- floor((numeric_date %% 1) * 60)
date_string <- paste0(hours, ":", minutes)
return(date_string)
}
1
Here is solution using tidyverse
library(tidyverse)
df <- data.frame(x = c(9.5, 9.75, 9, 9.25))
df %>%
mutate(
y = paste0(floor(x), ":", str_pad((x %% 1) * 60, 2, "right", "0"))
)
x y
1 9.50 9:30
2 9.75 9:45
3 9.00 9:00
4 9.25 9:15