来自?POSIXlt
:
从 R 3.5.0 开始,可以通过[
使用两个索引进行索引来提取和替换单个组件(参见示例)。
这个例子有点不透明,但显示了这个想法:
leapS[1 : 5, "year"]
但是,如果您查看源代码,您可以看到发生了什么:
`[.POSIXlt`
#> function (x, i, j, drop = TRUE)
#> {
#> if (missing(j)) {
#> .POSIXlt(lapply(X = unclass(x), FUN = "[", i, drop = drop),
#> attr(x, "tzone"), oldClass(x))
#> }
#> else {
#> unclass(x)[[j]][i]
#> }
#> }
#> <bytecode: 0x7fbdb4d24f60>
#> <environment: namespace:base>
它使用i
to subset unclass(x)
,其中x
是 POSIXlt 对象。因此,在 R 3.5.0 中,您可以使用[
向量中的日期时间索引并在您想要的日期时间部分前面加上前缀:
my.timedate <- as.POSIXlt('2016-01-01 16:00:00')
my.timedate[1, 'hour']
#> [1] 16
as.POSIXlt(seq(my.timedate, by = 'hour', length.out = 10))[2:5, 'hour']
#> [1] 17 18 19 20
请注意,$
子集仍然照常工作:
my.timedate$hour
#> [1] 16