Baccara
Baccara

Reputation: 13

Formatting numeric values to time in R

I want to format my numeric sleep minutes in a data frame to time in R. For example, this is what the data frame looks like:

TotalMinutesAsleep 327

sleep.day.1$TotalMinutesAsleep <- hms(sleep.day.1$TotalMinutesAsleep)                         

I need a quick and easy solution.

Thx,

Upvotes: 1

Views: 95

Answers (2)

TarJae
TarJae

Reputation: 78937

We coul use hms part of the tidyverse: A simple class for storing time-of-day values

library(hms)
hms(sleep.day.1$TotalMinutesAsleep*60)

output:

05:27:00

Upvotes: 1

akrun
akrun

Reputation: 887213

If these values are in minutes, convert to seconds and use seconds_to_period

library(lubridate)
period1 <- seconds_to_period(sleep.day.1$TotalMinutesAsleep * 60)

then, we may format it with

sprintf('%02d:%02d:%02d', period1@hour, period1@minute, second(period1))

Upvotes: 1

Related Questions