Home > Mobile >  How to convert 24-hour numeric values to time using lubridate? (R)
How to convert 24-hour numeric values to time using lubridate? (R)

Time:03-23

library(lubridate)
df <- tibble(var1 = c(0, 30, 830, 1400, NA), var2 = c("A", "A", "A", "A", "A"))

I have a set of numeric values representing 24 hours, e.g., 0 = 0:00, 30 = 0;30, 830 = 8:30, 1400 = 14:00. I would like to convert these values to a time field in lubridate. However, I get the following message when I try using hm(df)

Warning message:
In .parse_hms(..., order = "HM", quiet = quiet) :
  Some strings failed to parse, or all strings are NAs

CodePudding user response:

First add a variable number of leading zeroes, then convert to posixct and at last extract just the hours and minutes.

strftime(strptime(sapply(paste0("0000", df), function(i) substring(i, nchar(i) - 3, nchar(i))), "%H%M"), format = "%H:%M")

   00000   000030  0000830 00001400   0000NA 
 "00:00"  "00:30"  "08:30"  "14:00"       NA 

CodePudding user response:

If your vector is numeric, then the hours are given by how many hundreds a number has, and the minutes are the remainder of dividing by 100. So instead of string parsing, you can do:

seconds_to_period(60 * df %% 100   3600 * df %/% 100)
#> [1] "0S"        "30M 0S"    "8H 30M 0S" "14H 0M 0S" NA 

This gives the result in lubridate's period format, as using hm would.

  •  Tags:  
  • r
  • Related