1

Inside a function a need to convert some number, in general in range of 20 to 200, in to difftime and show via format as expected time needed to finish.

as.difftime has got a useful units="auto" so it will use "sec" say for 20 secs and "mins" for 60+ secs...

But it says also

> as.difftime(100, units="auto")
Error in as.difftime(100, units = "auto") : 
  need explicit units for numeric conversion

How can I avoid that?

EDIT: Current workaround

> (Sys.time()+100)-Sys.time()
Time difference of 1.666667 mins
4

1 回答 1

3

lubridate替代品吗?

library(lubridate)
new_difftime(second = 20)
# Time difference of 20 secs

new_difftime(second = 60)
# Time difference of 1 mins

new_difftime(second = 240)
# Time difference of 4 mins

new_difftime(second = 1000000)
# Time difference of 11.57407 days

# new_difftime creates an object of same class as as.difftime does. 
class(as.difftime(20, units = "secs"))
# [1] "difftime"

class(new_difftime(second = 20))
# [1] "difftime"

也可以指定几个单位的输入值。例如从?new_difftime

new_difftime(second = 3, minute = 1.5, hour = 2, day = 6, week = 1)
# Time difference of 13.08441 days
于 2013-09-17T15:46:58.153 回答