R中的奇怪POSIXct函数行为 [英] Odd POSIXct Function Behavior In R

查看:93
本文介绍了R中的奇怪POSIXct函数行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用R中的POSIXct数据类型。在我的工作中,我合并了一个在向量中返回两个POSIXct日期的函数。但是,我发现了一些意外的行为。我写了一些示例代码来说明我的问题:

I'm working with the POSIXct data type in R. In my work, I incorporate a function that returns two POSIXct dates in a vector. However, I am discovering some unexpected behavior. I wrote some example code to illustrate my problem:

# POSIXct returning issue:

returnTime <- function(date) {

  oneDay <- 60 * 60 * 24
  nextDay <- date + oneDay

  print(date)
  print(nextDay)

  return(c(date, nextDay))

}

myTime <- as.POSIXct("2015-01-01", tz = "UTC")

bothDays <- returnTime(myTime)
print(bothDays)

函数中的打印语句给出:

The print statements in the function give:

[1] "2015-01-01 UTC"
[1] "2015-01-02 UTC"

虽然代码末尾的print语句给出:

While the print statement at the end of the code gives:

[1] "2014-12-31 19:00:00 EST" "2015-01-01 19:00:00 EST"

我了解 正在发生,但我不知道为什么。这可能是一个简单的错误,使我难以理解,但我确实很困惑。我不明白为什么时区会在回程时改变。该类也仍然是POSIXct,只是时区已更改。

I understand what is happening, but I don't see as to why. It could be a simple mistake that is eluding me, but I really am quite confused. I don't understand why the time zone is changing on the return. The class is still POSIXct as well, just the time zone has changed.

此外,我做的与上述相同,只是返回了日期和时区中的一个没有改变。我现在可以解决此问题,但想看看是否有人对我的问题有任何见解。预先谢谢您!

Additionally, I did the same as above, but just returned one of the dates and the date's timezone did not change. I can work around this for now, but wanted to see if anyone had any insight to my problem. Thank you in advance!

感谢您的帮助。我改为:

Thanks for the help below. I instead did:

 return(list(date, nextDay))

,这解决了我的时区下降问题。

and this solved my issue of the time zone being dropped.

推荐答案

问题在于函数 c 删除了时区属性:

The problem is that the function c removes the timezone attribute:

attributes(myTime)
#$class
#[1] "POSIXct" "POSIXt" 
#
#$tzone
#[1] "UTC"

attributes(c(myTime))
#$class
#[1] "POSIXct" "POSIXt"

要修复,您可以例如使用 data.table 中的 setattr 函数,就地修改属性:

To fix, you can e.g. use the setattr function from data.table, to modify the attribute in place:

(setattr(c(myTime), 'tzone', attributes(myTime)$tzone))
#[1] "2015-01-01 UTC"

这篇关于R中的奇怪POSIXct函数行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆