简体   繁体   English

读取不同长度的时间数据并使它们在R中相同

[英]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 . 我正在将一些时间数据从文本文件读入R。数据在N.Time列中。 Some of the data in N.Time has hours, minutes, and seconds (for example 1:45:02). N.Time某些数据具有小时,分钟和秒(例如1:45:02)。 Instances that are under an hour just have minutes and seconds (for example 34:25) 一个小时以下的实例只有几分钟和几秒钟(例如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. 如果我使用%H:%M:%S格式,则所有没有小时的实例都将转换为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). 如果我使用%M:%S格式,则有几个小时的实例会混乱(例如1:45:02变为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? 理想情况下,将小时数添加到所有没有小时的实例中的“ 00:”?

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: 如果除了丢失的小时数以外,所有时间都具有相同的固定格式,则用00:填充小时数的正则表达式不是太复杂:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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