r - 类 "POSIXlt"的 R 对象是否为 "list"?

标签 r list

documentation of the class POSIXlt POSIXlt 类的对象是命名列表。
确实:

> tm <- strptime( "24-12-2015 05:28:12", format="%d-%m-%Y %H:%M:%S", tz="UTC" )
> class(tm)
[1] "POSIXlt" "POSIXt" 

> tm$sec
[1] 12

> tm$min
[1] 28

> tm$hour
[1] 5

> tm$mday
[1] 24

> tm$mon
[1] 11

> tm$year
[1] 115

> tm$wday
[1] 4

> tm$yday
[1] 357

> tm$isdat
NULL

> tm$zone
NULL

> tm$gmtoff
NULL

documentation of the class listis.list(tm)为真当且仅当 tm是一个列表或配对列表,
is.pairlist(tm)为真当且仅当 tm是一个pairlist 或NULL。
> is.list(tm)
[1] TRUE
> is.pairlist(tm)
[1] FALSE

因此 tm必须是一个列表。

但是“列表”不是“POSIXlt”的父类(super class):
> is(tm)
[1] "POSIXlt"  "POSIXt"   "oldClass"
> extends("POSIXlt")
[1] "POSIXlt"  "POSIXt"   "oldClass"
extends否定“POSIXlt”范围是否为“列表”的问题,答案甚至不是“可能”:
> extends("POSIXlt","list")
[1] FALSE

此外,
> is("POSIXlt","list")
[1] FALSE
> is(tm,"list")
[1] FALSE

documentation of is 这意味着 tm不能被视为来自“列表”。特别是tm不是一个列表。
但如果 tm不能被视为来自“列表”,为什么 as成功胁迫tm到列表?as(tm.list无疑是一个列表,而 as.list(tm)tm是相同的:
> as(tm,"list")
[[1]]
[1] 12

[[2]]
[1] 28

[[3]]
[1] 5

[[4]]
[1] 24

[[5]]
[1] 11

[[6]]
[1] 115

[[7]]
[1] 4

[[8]]
[1] 357

[[9]]
[1] 0

> class(as(tm,"list"))
[1] "list"
> is.list(as(tm,"list"))
[1] TRUE
> is(as(tm,"list"),"list")
[1] TRUE
> identical(tm,as.list(tm))
[1] TRUE
as(tm,"list")确实具有 POSIXlt 类的文档中指定的组件,但名称已消失。

成为一个列表意味着什么?是 tm一个列表与否?

最佳答案

这是一个带有 c("POSIXct", "POSIXt") 的命名列表类和 tzone属性:

POSIXlt = Named list + class + tzone attribute



事实上,我们可以从一个命名列表 L 建立或制造这样一个对象。通过添加 classtzone属性是这样的:
L <- list(sec = 12, min = 28L, hour = 5L, mday = 24L, mon = 11L, 
    year = 115L, wday = 4L, yday = 357L, isdst = 0L)

tm0 <- L # start with list L
class(tm0) <- c("POSIXlt", "POSIXt")  # add class
attr(tm0, "tzone") <- "UTC"  # add tzone

tm <- strptime( "24-12-2015 05:28:12", format="%d-%m-%Y %H:%M:%S", tz="UTC" )
identical(tm0, tm)
## [1] TRUE

我们可以恢复命名列表 L来自 tm通过删除 classtzone属性:
tm <- strptime( "24-12-2015 05:28:12", format="%d-%m-%Y %H:%M:%S", tz="UTC" )  # start w tm
L0 <- unclass(tm)  # remove class
attr(L0, "tzone") <- NULL  # remove tzone
identical(L0, L)
## [1] TRUE

关于r - 类 "POSIXlt"的 R 对象是否为 "list"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34454916/

相关文章:

r - 从 ggplot2 中获取向量

java - 如何从ArrayList打印特定项目

R:创建具有特定数量随机数的向量

r - 如何降低 Shiny 输入小部件的高度?

r - 在 R 中保存高分辨率图像

function - 将变量名传递给 r 中的函数

python - 有人可以向我解释这个非常基本的 Python 代码吗?

java - 需要帮助转换 Java 列表/集合或其他内容

python - 查找具有不同键的 2 个字典列表之间的不同值

python - python 列表连接中的奇怪行为