1

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,

Peter
  • 11,500
  • 5
  • 21
  • 31
Baccara
  • 13
  • 2
  • Thanks again, I done that and created a new data frame. Now, I am struggling with plotting this data. Mine is all over the place and most tutorials go over dates and not hours and minutes. – Baccara Sep 22 '21 at 21:43

2 Answers2

1

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))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Ahhh, library(hms), I will try that. Thank you! – Baccara Sep 20 '21 at 21:28
  • sprintf? I will use it, do you have a link to explain? – Baccara Sep 20 '21 at 21:29
  • @Baccara the `seconds_to_period` returns a `period` class object and `sprintf` is just doing the formatting on the extracted period elements with `@` – akrun Sep 20 '21 at 21:30
  • I have created a new data frame with everything formatted. I am struggling with graphing it. Is there a package that will help? – Baccara Sep 22 '21 at 22:33
  • @Baccara you may post as a new question. If the current solution works, please consider to accept solution – akrun Sep 22 '21 at 22:34
1

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
TarJae
  • 72,363
  • 6
  • 19
  • 66