自动格式化时差

时间:2013-09-17 15:02:46

标签: r date-format

在函数内部,需要将一些数字(通常在20到200之间)转换为difftime,并通过format显示完成所需的预期时间。

as.difftime有一个有用的units="auto"所以它会使用“sec”表示20秒,“mins”表示60秒以上......

但它也说

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

我该如何避免?

编辑:当前的解决方法

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

1 个答案:

答案 0 :(得分: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