如何使用POSIX DateTime维护时区并避免R中强制引入的NA?

not*_*odr 1 datetime r time-series posixct

我创建了一个时间序列数据框,我将用它来合并其他时间序列数据.

dates2010 <- seq(as.POSIXct("2010-06-15 00:00:00", tz = "GMT"), as.POSIXct("2010-09-15 23:00:00", tz = "GMT"), by="hour")  # make string of DateTimes for summer 2010
dates2011 <- seq(as.POSIXct("2011-06-15 00:00:00", tz = "GMT"), as.POSIXct("2011-09-15 23:00:00", tz = "GMT"), by="hour")  # make string of DateTimes for summer 2011
dates <- c(dates2010, dates2011)                           # combine the dates from both years
sites <- c("a", "b", "c")                                  # make string of all sites
datereps <- rep(dates, length(sites))                      # repeat the date string the same number of times as there are sites
sitereps <- rep(sites, each = length(dates))               # repeat each site in the string the same number of times as there are dates 
n <- data.frame(DateTime = datereps, SiteName = sitereps)  # merge two strings with all dates and all sites
n <- n[order(n$SiteName, n$Date),]                         # re-order based on site, then date
Run Code Online (Sandbox Code Playgroud)

如果我运行上面的代码,'dates2010'和'dates2011'是GMT格式:dates2010[1]"2011-06-15 00:00:00 GMT".但是当我因某种原因创建对象'dates'时格式切换到EST:dates[1] "2010-06-14 19:00:00 EST"

也许它与POSIX类有关?

class(dates2010)
[1] "POSIXct" "POSIXt"
Run Code Online (Sandbox Code Playgroud)

我尝试将R的默认时区更改为GMT以避免时区切换问题.当我尝试对数据帧'n'进行排序并将其他数据帧合并为'n'时,这会导致NA coersion错误.

n <- n[order(n$SiteName, n$Date),]
Warning message:
In xtfrm.POSIXct(x) : NAs introduced by coercion
Run Code Online (Sandbox Code Playgroud)

有关如何保持时区不变并避免NA强制错误的任何想法?谢谢!

Ric*_*ven 5

c()丢弃属性.因此,在您创建时dates,时区已被删除,并且它会自动默认为当前区域设置.幸运的是,您可以structure()在那里使用和设置时区.

dates <- structure(c(dates2010, dates2011), tzone = "GMT")
head(dates)
# [1] "2010-06-15 00:00:00 GMT" "2010-06-15 01:00:00 GMT" 
# [3] "2010-06-15 02:00:00 GMT" "2010-06-15 03:00:00 GMT"
# [5] "2010-06-15 04:00:00 GMT" "2010-06-15 05:00:00 GMT"
Run Code Online (Sandbox Code Playgroud)

如果dates已创建,则可以tzone稍后添加/更改该属性.

attr(dates, "tzone") <- "GMT"
Run Code Online (Sandbox Code Playgroud)