提取运算符 '['- POSIXlt 未分类列表打印日期时间

Extract operator '['- POSIXlt unclassed list prints datetime

目的: 打印从POSIXlt对象中获取的列表的第一个元素。

代码:

> x <- as.POSIXlt(Sys.time())
> x
[1] "2016-06-18 23:51:14 IST"
> x[1]
[1] "2016-06-18 23:51:14 IST"
> x[[1]]
[1] 14.70887
> temp <- list(999,23,3)  
> temp[1]
[[1]]
[1] 999
> temp[[1]]
[1] 999

当我们使用单次提取访问 POSIXlt 对象 x 时,将打印整个日期时间,但是当我们类似地访问另一个列表 (temp) 时,将打印第一个元素作为列表(如单括号提取 returns同一个对象)。第一个元素虽然是在我对 R 使用双括号 extract.New 时检索到的,所以任何人都可以对此有所了解吗?

从普通列表中索引 POSIXlt 对象的异常行为与 [ 运算符是如何为 POSIXlt class 定义的有关。如果你查看 [.POSIXlt 的源代码,你会发现它的定义方式非常反直觉。它不是对列表进行子集化,而是遍历列表,选取每个元素并重新分配属性,这使得 x[1]x 基本相同。所以我的评论被 length(l) 和 returns 误导了,这是因为 class POSIXltlength 函数是以这种方式定义的。更仔细地检查这两个函数定义,您会发现为什么行为不正常 list:

[ POSIXlt:

的函数定义
`[.POSIXlt`
function (x, ..., drop = TRUE) 
{
    val <- lapply(X = x, FUN = "[", ..., drop = drop)   
    # note how the above line has looped through the original list and collected all of them
    attributes(val) <- attributes(x)
    val
}
<bytecode: 0x105dc90d8>
<environment: namespace:base>

length POSIXlt:

的函数定义
length.POSIXlt
function (x) 
length(x[[1L]])     # this will always return one
<bytecode: 0x102270a68>
<environment: namespace:base>

而且由于 [[ 没有为 POSIXlt class 定义,它仍然会像普通列表一样工作。