JanLauGe
JanLauGe

Reputation: 2335

Convert decimal number double to hour, time, or difftime in R

I have a vector of doubles specifying hours in a day, such as the example given below. 6.50 would correspond to 06:30 in hh:mm format and so on.

ts <- c(6.50, 7.00, 7.25, 7.45, 8.00)

I would like to convert this to a date or time format. The solution that I could come up with involves striping the decimal places from the number and converting them to minutes, but this feels a bit "hacky", e.g.

library(lubridate)
hm(paste(floor(ts), (ts - floor(ts)) * 60, sep = ':'))

Surely there is a better way to do this?

Upvotes: 2

Views: 2708

Answers (3)

CPak
CPak

Reputation: 13581

Sticking only with lubridate

library(lubridate)
as.period(as.duration(days(x=1))*(ts/24))
# "6H 30M 0S" "7H 0M 0S"  "7H 15M 0S" "7H 27M 0S" "8H 0M 0S"

Upvotes: 1

G. Grothendieck
G. Grothendieck

Reputation: 269441

Try this:

library(chron)

times(ts / 24)
## [1] 06:30:00 07:00:00 07:15:00 07:27:00 08:00:00

This would also work:

library(chron)
library(lubridate)

hms(times(ts/24))
## [1] "6H 30M 0S" "7H 0M 0S"  "7H 15M 0S" "7H 27M 0S" "8H 0M 0S" 

Upvotes: 3

Sagar
Sagar

Reputation: 2914

> lubridate::hm(ts)
[1] "6H 50M 0S" "7H 0M 0S"  "7H 25M 0S" "7H 45M 0S" "8H 0M 0S"

Alternative to the request (what you already have in your question):

> paste(floor(ts), round((ts-floor(ts))*60), sep=":")
[1] "6:30" "7:0"  "7:15" "7:27" "8:0"

Upvotes: 0

Related Questions