gpt4 book ai didi

r - 将列表转换为向量时,为什么 POSIXct 转换为数字

转载 作者:行者123 更新时间:2023-12-01 23:09:46 24 4
gpt4 key购买 nike

我有一个 list redDressTweetsstatus es. status是一个带有字段的类 created .我试图形成一个发布推文的时间列表。这是我尝试这样做的方法

times <- unlist(lapply(redDressTweets, function(tweet) {tweet$created }))

输出是一个数字向量:
[1] 1478044029 1477954062 1477909847 1477887746 1477832560 1477640940 1477640939
[8] 1477628031 1477540826

但是 redDressTweets[[1]]$created的类是 "POSIXct" "POSIXt" .

为什么会发生这种情况,如何阻止它将 POSIXct 转换为数字?

最佳答案

您可以像这样更轻松地重现:

x <- list(as.POSIXct("2016-11-02"), as.POSIXct("2016-11-03"))
unlist(x)
#[1] 1478041200 1478127600
unlist组合列表中的值。 POSIXct的内部表示变量是数值。他们只是一个 POSIXct由于属性而变量,最重要的是 class属性。一个列表可以容纳所有类型的对象。文档说:

Where possible the list elements are coerced to a common mode during the unlisting, and so the result often ends up as a character vector. Vectors will be coerced to the highest type of the components in the hierarchy NULL < raw < logical < integer < double < complex < character < list < expression: pairlists are treated as lists.



请注意,它说的是“通用模式”,而不是通用类。由于类可以是任何东西并且可以强制任何类型的底层结构(例如,甚至可能无法以有意义的方式组契约(Contract)一类的两个对象), unlist只是去除所有属性(除了 list,其中所有元素都是因子)。可以处理 POSIXctfactor 这样的值值,但事实并非如此(并且可能会影响性能)。

您无法避免这种情况,但可以轻松修复它:
y <- unlist(x)
attributes(y) <- attributes(x[[1]])
y
#[1] "2016-11-02 CET" "2016-11-03 CET"

显然,这假设所有列表元素都具有相同的时区属性。

关于r - 将列表转换为向量时,为什么 POSIXct 转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40378355/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com