Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

r - Convert hour:minute:second (HH:MM:SS) string to proper time class

In the following data frame the 'time' column is character in the format hour:minute:second

id <- c(1, 2, 3, 4)
time <- c("00:00:01", "01:02:00", "09:30:01", "14:15:25")
df <- data.frame(id, time)

How can I convert 'time' column to a dedicated time class, so that I can perform arithmetic calculations on it?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the function chron in package chron:

time<-c("00:00:01", "01:02:00", "09:30:01", "14:15:25")

library(chron)
x <- chron(times=time)

x
[1] 00:00:01 01:02:00 09:30:01 14:15:25

Do some useful things, like calculating the difference between successive elements:

diff(x)
[1] 01:01:59 08:28:01 04:45:24

chron objects store the values internally as a fraction of seconds per day. Thus 1 second is equivalent to 1/(60*60*24), or 1/86400, i.e. 1.157407e-05.

So, to add times, one simple option is this:

x + 1/86400
[1] 00:00:02 01:02:01 09:30:02 14:15:26

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...