POSIXlt组件的提取在R 3.4.4中运行良好,但R 3.5.0中的错误.为什么?

Geo*_*aga 6 datetime r posixlt

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
Run Code Online (Sandbox Code Playgroud)

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']]) 
Run Code Online (Sandbox Code Playgroud)

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

Dir*_*tel 9

认为这是R 3.5.0中已知的变化,其中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:~$ 
Run Code Online (Sandbox Code Playgroud)

而对于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:~$ 
Run Code Online (Sandbox Code Playgroud)

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

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

* Single components of "POSIXlt" objects can now be extracted and
  replaced via [ indexing with 2 indices.
Run Code Online (Sandbox Code Playgroud)


Hen*_*rik 5

?DateTimeClasses(同?as.POSIXlt):

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

参见R NEWS CHANGES IN R 3.5.0中的类似描述.

从而:

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
Run Code Online (Sandbox Code Playgroud)

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


ali*_*ire 5

来自?POSIXlt:

从R 3.5.0开始,可以通过[索引用两个索引来提取和替换单个组件(参见示例).

这个例子有点不透明,但显示了这个想法:

leapS[1 : 5, "year"]
Run Code Online (Sandbox Code Playgroud)

但是,如果您查看源代码,您可以看到发生了什么:

`[.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>
Run Code Online (Sandbox Code Playgroud)

i用于子集unclass(x),xPOSIXlt对象在哪里.因此,对于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
Run Code Online (Sandbox Code Playgroud)

请注意,$子集仍然照常工作:

my.timedate$hour
#> [1] 16
Run Code Online (Sandbox Code Playgroud)