我创建了一个时间序列数据框,我将用它将其他时间序列数据合并到。
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
如果我运行上述代码,&#39; dates2010&#39;和&#39; dates2011&#39;采用GMT格式:dates2010[1]
&#34; 2011-06-15 00:00:00 GMT&#34;。
但是当我创建对象&#39; dates&#39;由于某种原因,格式切换到EST:dates[1]
&#34; 2010-06-14 19:00:00 EST&#34;
也许它与POSIX类有关?
class(dates2010)
[1] "POSIXct" "POSIXt"
我试图change the default time zone for R转到GMT以避免时区切换问题。当我尝试订购数据框时,这会导致NA错误错误。并将其他数据框合并到&#39; n&#39;。
n <- n[order(n$SiteName, n$Date),]
Warning message:
In xtfrm.POSIXct(x) : NAs introduced by coercion
有关如何保持时区不变并避免NA强制错误的任何想法?谢谢!
答案 0 :(得分: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"
如果已创建dates
,您可以稍后添加/更改tzone
属性。
attr(dates, "tzone") <- "GMT"