将整数转换为ITime?

5

我正在研究使用新的data.table日期和时间格式。由于ITime在底层是以整数形式存储的(自午夜以来的秒数):

x <- as.ITime( "10:25:00" )
i <- as.integer( x )
i
[1] 37500

看起来将整数(假设小于24*60*60)转换为 ITime 应该很容易,但我找不到如何实现:

as.ITime( i )
Error in as.POSIXlt.numeric(x, ...) : 'origin' must be supplied

as( i, "ITime" )
Error in as(i, "ITime") : 
  no method or default for coercing “integer” to “ITime”

提供一个起始时间(我猜是通过 as.POSIX... 传递)确实有所帮助,但即使这样,只有在您将 tz 指定为 "UTC" 时才能得到正确的值(至少对于我的语言环境而言):

as.ITime( i, origin = "1970-01-01 00:00:00" )
[1] "20:25:00"

as.ITime( i, origin = "1970-01-01 00:00:00", tz = "UTC" )
[1] "10:25:00"

# note that the date seems necessary but irrelevant here
as.ITime( i, origin = "2000-01-01 00:00:00", tz = "UTC" )
[1] "10:25:00"

我所说的是类似于我有时与chron::times一起使用的东西:
x <- chron::times( "10:25:00" )

n <- as.numeric( x )
n
[1] 0.4340278

chron::times( n )
[1] 10:25:00

是否有一个类似的方法(除了使用整数而不是数字/双精度/浮点数)可用于 ITime 类?

请注意,我知道与 IDateDate 等相同的“来源要求”问题,但对我来说这更有意义,因为将 origin="1970-01-01" 作为时间的起点与使用“午夜”作为起点相比要少得多(我使用一些数据源对哪个日期应该被称为“起点”有不同的想法)。


2
setattr类应该可以做到。 - Frank
确实如此,谢谢Frank!如果您愿意,可以将您的评论转化为答案,我会接受它。 - rosscova
你如何通过 setattr 实现这个? - David Arenburg
例如,@DavidArenburg的setattr(1:10, "class", "ITime")基本上就是我想要实现的。如果您有其他方法,我很乐意听取。 - rosscova
2
哦,不错啊,没想到函数可以作为值使用,而且名称实际上是以这种方式解析的。 - David Arenburg
1个回答

5
这可以正常工作:
library(data.table)
DT = data.table(int = 37500L)
DT[, setattr(int, "class", "ITime")]

#         int
# 1: 10:25:00

或者
int = 37500L
setattr(int, "class", "ITime")

# "10:25:00"

这比 as.ITime 更快吗? - MichaelChirico
@MichaelChirico as.ITime(37500L) # error?这应该相当快,因为它只是向向量添加属性,所以在较长的向量上不会增加更多的成本。 - Frank
1
呵呵,我是指 as.ITime(37500, origin = '1970-01-01 00:00:00', tz = 'UTC')... 看起来使用 setattr 应该更快,但另一方面,我觉得在这种情况下应该尽可能加速 as.ITime - MichaelChirico

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接