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
734 views
in Technique[技术] by (71.8m points)

r - Divide two difftime objects

I have three time (POSIXct) objects t1, t2, t3 which specify the time duration to complete a task.

I found t1, t2, t3 by doing the following:

t1 <- as.POSIXct("2016-10-30 13:53:34") - as.POSIXct("2016-10-30 13:35:34")
t2 <- as.POSIXct("2016-10-30 14:53:34") - as.POSIXct("2016-10-30 14:35:34")
t3 <- as.POSIXct("2016-10-30 15:50:34") - as.POSIXct("2016-10-30 15:40:34")

I want to find the ratios t1/t3 and t2/t3. However, I get the following error:

t1/t3
# Error in `/.difftime`(t1, t3) : 
#   second argument of / cannot be a "difftime" object

I understood that two difftime objects cannot be divided. Is there any way that I could find the result of dividing two difftime objects?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

To divide by a difftime you must convert it to numeric. If, as you stated in a comment, you would like the answer to be expressed in seconds, you can specify the 'secs' units. For example:

t1/as.double(t3, units='secs')

As @JonathanLisic notes, as.double does not generally take a units parameter, and this won't work for generic time classes. It is the S3 method for difftime which takes the parameter.


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

...