简体   繁体   中英

How to convert a time interval saved as an integer to a date object in R?

I have a dataset with an integer variable that denotes observations taken in 5-minute intervals throughout a full day, but when it counts to 55, it increments the hour. so following "55" is "100", then "105"... and following "955" is "1000". Essentially it's an hh:mm 24-hour clock, but omits the preceding zeroes. I need to convert these to time objects, but haven't found a simple function within the lubridate package.

My last resort would be to convert this variable to a string, use "if" loops to paste on 3, 2, or 1 zero to each one so I could call parse_date_time(data$interval, "H?M!") but I'm wondering if there's a more elegant solution that I'm not aware of?

Use sprintf to convert the integer into fixed-width string and then convert it into time object.

x <- c(50, 55, 100, 105, 955, 1000)
as.POSIXct(sprintf("%04d", x), format = "%H%M", tz = "UTC")

#[1] "2019-11-04 00:50:00 UTC" "2019-11-04 00:55:00 UTC" "2019-11-04 01:00:00 UTC"
#[4] "2019-11-04 01:05:00 UTC" "2019-11-04 09:55:00 UTC" "2019-11-04 10:00:00 UTC"

Similar results can also be achieved with stringr::str_pad and strptime

strptime(stringr::str_pad(x, 4, pad = 0), format = "%H%M", tz = "UTC")

Or using parse_date_time

lubridate::parse_date_time(sprintf("%04d", x), "HM")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM