b=c(ymd("2011-6ren">
gpt4 book ai didi

r - lubridate 解析日期休息一天

转载 作者:行者123 更新时间:2023-12-01 09:58:20 31 4
gpt4 key购买 nike

当我将单个日期解析时,它解析准确

> ymd("20011001")
[1] "2001-10-01 UTC"

但是当我尝试创建一个日期向量时,它们都会在一天假时出现:

> b=c(ymd("20111001"),ymd("20101001"),ymd("20091001"),ymd("20081001"),ymd("20071001"),ymd("20061001"),ymd("20051001"),ymd("20041001"),ymd("20031001"),ymd("20021001"),ymd("20011001"))
> b
[1] "2011-09-30 19:00:00 CDT" "2010-09-30 19:00:00 CDT" "2009-09-30 19:00:00 CDT"
[4] "2008-09-30 19:00:00 CDT" "2007-09-30 19:00:00 CDT" "2006-09-30 19:00:00 CDT"
[7] "2005-09-30 19:00:00 CDT" "2004-09-30 19:00:00 CDT" "2003-09-30 19:00:00 CDT"
[10] "2002-09-30 19:00:00 CDT" "2001-09-30 19:00:00 CDT"

我该如何解决这个问题???非常感谢。

最佳答案

我不声称完全理解这里发生了什么,但最接近的问题是 c() 剥离属性,所以在 POSIX 上使用 c() [c?]t vector 将其从 UTC 更改为您的语言环境指定的时区 剥离时区属性,将其搞乱(即使您将时区设置为与您指定的时区一致语言环境)。在我的系统上:

library(lubridate)
(y1 <- ymd("20011001"))
## [1] "2001-10-01 UTC"
(y2 <- ymd("20011002"))
c(y1,y2)
## now in EDT (and a day earlier/4 hours before UTC):
## [1] "2001-09-30 20:00:00 EDT" "2001-10-01 20:00:00 EDT"
(y12 <- ymd(c("20011001","20011002")))
## [1] "2001-10-01 UTC" "2001-10-02 UTC"
c(y12)
## back in EDT
## [1] "2001-09-30 20:00:00 EDT" "2001-10-01 20:00:00 EDT"

您可以明确设置时区...

y3 <- ymd("20011001",tz="EDT")
## [1] "2001-10-01 EDT"

但是c()还是有问题。

(y3c <- c(y3))
## [1] "2001-09-30 20:00:00 EDT"

所以有两种解决方案

  • 转换一个字符向量而不是将对象一个一个转换后再组合
  • 合并后恢复tzone属性。

例如:

 attr(y3c,"tzone") <- attr(y3,"tzone")

@Joran 指出,这几乎可以肯定是将 c() 应用于 POSIX[c?]t 对象的一般属性,而不是特定的 lubridate相关。我希望有人能插话并解释这是否是一个众所周知的设计决策/缺陷/缺陷。

更新:有人讨论这个on R-help in 2012 , 和 Brian Ripley 评论:

But in any case, the documentation (?c.POSIXct) is clear:

  Using ‘c’ on ‘"POSIXlt"’ objects converts them to the current time
zone, and on ‘"POSIXct"’ objects drops any ‘"tzone"’ attributes
(even if they are all marked with the same time zone).

So the recommended way is to add a "tzone" attribute if you know what you want it to be. POSIXct objects are absolute times: the timezone merely affects how they are converted (including to character for printing).

如果 lubridate 添加一个方法来执行此操作可能会很好......

关于r - lubridate 解析日期休息一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20863225/

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