Search code examples
rtime-seriesposixct

"character string is not in a standard unambiguous format" when data is numeric


I have data in the form of minutes after midnight. For example, "70" corresponds to 1:10am. I am trying to convert it to HH:mm in R so that I can do some time series analyses.

Here is the code I have tried:

xtime <- as.numeric(as.character(occur_dat$Minutes_After_12am))


x_time <- format(as.POSIXct(xtime, origin = "00:00"), format = "%H:%M")

I verified that xtime is a numeric vector, and it is. I am not sure why I keep getting the "character string is not in a standard unambiguous format" error. Similar questions appear to be resolved with the first line of code (as.numeric), so I am at a loss.


Solution

  • Use a period/time class from a package. I like package data.table but I think lubridate and chron also provide such classes.

    library(data.table)
    
    #75 minutes after midnight
    x <- as.ITime(75 * 60)
    #"01:15:00"
    sprintf("%02d:%02d", hour(x), minute(x))
    #[1] "01:15"