Odd POSIXct Function Behavior In R

2019-02-23 21:10发布

问题:

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"

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"

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.

回答1:

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"

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"


回答2:

From ?c.POSIXct:

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).

See also here.