Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd POSIXct Function Behavior In R

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.

like image 675
giraffehere Avatar asked Mar 14 '23 20:03

giraffehere


1 Answers

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.

like image 138
rcs Avatar answered Mar 17 '23 15:03

rcs