6

1) R 版本 3.4.4 (2018-03-15)

my.timedate <- as.POSIXlt('2016-01-01 16:00:00')  
# print(attributes(my.timedate))  
print(my.timedate[['hour']])  

[1] 16

2) R 版本 3.5.0 (2018-04-23)

my.timedate <- as.POSIXlt('2016-01-01 16:00:00')  
# print(attributes(my.timedate))  
print(my.timedate[['hour']]) 

FUN(X[[i]], ...) 中的错误:下标越界

4

3 回答 3

9

认为这是 R 3.5.0 中的一个已知变化,其中 a 的列表元素POSIXlt需要显式解包。使用 R 3.5.0:

edd@rob:~$ docker run --rm -ti r-base:3.5.0 \
               R -q -e 'print(unclass(as.POSIXlt("2016-01-01 16:00:00")[["hour"]])'
> print(unclass(as.POSIXlt("2016-01-01 16:00:00"))[["hour"]])
[1] 16
> 
> 
edd@rob:~$ 

而在 R 3.4.* 中,不需要unclass()你展示的:

edd@rob:~$ docker run --rm -ti r-base:3.4.3 \
               R -q -e 'print(as.POSIXlt("2016-01-01 16:00:00")[["hour"]])'
> print(as.POSIXlt("2016-01-01 16:00:00")[["hour"]])
[1] 16
> 
> 
edd@rob:~$ 

我没有找到相应的 NEWS 文件条目,所以不完全确定它是否是故意的......

编辑:正如其他人所指出的,相应的 NEWS 条目有点不透明

* Single components of "POSIXlt" objects can now be extracted and
  replaced via [ indexing with 2 indices.
于 2018-06-16T20:35:13.827 回答
5

来自?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>

它使用ito 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
于 2018-06-16T21:11:09.100 回答
5

?DateTimeClasses(同?as.POSIXlt):

从 R 3.5.0 开始,可以通过[使用两个索引进行索引来提取和替换单个组件

另请参阅R 3.5.0 中的 R 新闻更改中的类似描述。

因此:

my.timedate[1, "hour"]
# [1] 16

# or leave the i index empty to select a component
# from all date-times in a vector 
as.POSIXlt(c('2016-01-01 16:00:00', '2016-01-01 17:00:00'))[ , "hour"]
# [1] 16 17

另请参阅帮助文本中的示例

于 2018-06-16T21:07:03.627 回答