简体   繁体   中英

Reading time data of different lengths and making them the same in R

I am reading in some time data from a text file into R. The data is in column N.Time . Some of the data in N.Time has hours, minutes, and seconds (for example 1:45:02). Instances that are under an hour just have minutes and seconds (for example 34:25)

The data is read in as characters. I want to convert to times to perform calculations later. However the formatting is messing me up. If I use the %H:%M:%S format, all of the instances that don't have hours are converted to NA. If I use the %M:%S format, the instances that have hours get messed up (for example 1:45:02 becomes 00:01:05).

Any advice on how to get these two formats to work together? Ideally somehow just add 00: in the hours slot to all instances that don't have hours?

If all the times have the same fixed format apart from the missing hours issue, then the regex to fill in the hours with 00: isn't too complicated:

> times = c("1:45:02", "34:25")
> gsub("^(\\d\\d:\\d\\d)$", "00:\\1", times, perl = TRUE)
[1] "1:45:02"  "00:34:25"

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