I have a time in decimal format: 22,13 in hours and I would like to express this in R as HH:MM. I mean, 22:08 (depreciating seconds)
Anyone can help me?
I have a time in decimal format: 22,13 in hours and I would like to express this in R as HH:MM. I mean, 22:08 (depreciating seconds)
Anyone can help me?
The syntax %02.0f is to round the value to an integer and make it always be 2 units. Therefore, 7.8 minutes will be converted to character "08".
x <- c("22,13", "9,25", "7,8")
sprintf("%02d:%02.0f",
as.numeric(sub(",\\d+", "", x)),
as.numeric(sub("\\d+,", "0.", x)) * 60)
# [1] "22:08" "09:15" "07:48"
Scan the string into s as numeric, divide it by 24 so that we can convert it to times class (as times expects a fraction of a day), round it to minutes and remove the trailing :00
library(chron)
x <- c("22,13", "5,20") # test data
s <- scan(text = x, dec = ",", quiet = TRUE)
sub(":00$", "", round(times(s/24), "min")) ##
## [1] "22:08" "05:12"
If you prefer to truncate the seconds rather than to round to the nearest minute then replace round with trunc in the line marked ## or replace that entire line with:
format(as.chron(s/24), format = "%H:%M") # truncate
If y is the result of the line marked ## then these convert back to times class and to number of hours respectively. We have used round(..., 2) in the last line to get the same number of digits as the original input but if that is not important it could be omitted.
y <- c("22:08", "05:12")
tt <- times(paste0(y, ":00"))
tt
## [1] 22:08:00 05:12:00
round(24 * as.numeric(tt), 2)
## [1] 22.13 5.20