首先,我看一看?xts,意识到这是一个与时区有关的问题,并且似乎已经解决了该问题,但是我不明白为什么会这样。所以:我有一个简单的价格数据数据框架。当我将其转换为xts对象时,xts对象的第一个日期比数据框中的第一个日期早一天。如果我指定时区,则日期匹配问题将消失。我最初以为可能是因为xts()假定未指定TZ的order.by日期为UMT,而Sys.timezone()为我提供了“JST”,但我不明白为什么这会导致一个整天的日期... ?

问:为什么会这样?

require(xts)
aa <- structure(list(Date = structure(c(6822, 6823, 6824, 6825, 6826,
6829), class = "Date"), Open = c(2145, 2126, 2130, 2148, 2144,
2137), High = c(2148, 2131, 2141, 2152, 2146, 2151), Low = c(2124,
2111, 2128, 2140, 2135, 2136), Close = c(2124, 2120, 2141, 2140,
2140, 2149), Volume = c(0L, 0L, 0L, 0L, 0L, 0L)), .Names = c("Date",
"Open", "High", "Low", "Close", "Volume"), row.names = c(NA,
6L), class = "data.frame")

str(aa)
aa

bb <- xts(aa[5], order.by = aa$Date)
str(bb)
bb ## first date is a day earlier than the first day of the data frame

bb <- xts(aa[5], order.by = aa$Date, tzone = Sys.getenv("TZ"))
str(bb)
bb ## first dates in xts object and data frame match...

这是在:
sessionInfo():
R version 2.15.1 (2012-06-22)

Platform: i386-pc-mingw32/i386 (32-bit)

locale:
[1] LC_COLLATE=English_United Kingdom.1252
[2] LC_CTYPE=English_United Kingdom.1252
[3] LC_MONETARY=English_United Kingdom.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.1252

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods
[8] base

other attached packages:
 [1] gridExtra_0.9.1 scales_0.2.2    plyr_1.7.1      ggplot2_0.9.2.1
 [5] lubridate_1.2.0 quantmod_0.3-17 TTR_0.21-1      xts_0.8-8
 [9] zoo_1.7-9       Defaults_1.1-1

loaded via a namespace (and not attached):
 [1] colorspace_1.2-0   dichromat_1.2-4    digest_0.5.2       gtable_0.1.1
 [5] labeling_0.1       lattice_0.20-10    MASS_7.3-22        memoise_0.1
 [9] munsell_0.4        proto_0.3-9.2      RColorBrewer_1.0-5 reshape2_1.2.1
[13] stringr_0.6.1

最佳答案

我不知道,我无法确切地重现您的问题,但是我相信这与将Date强制转换为POSIXct并返回有关。

此行在xts函数的代码中:

if (inherits(order.by, "Date") && !missing(tzone))
    order.by <- .POSIXct(unclass(order.by) * 86400, tz = tzone)

在您的第一个电话中,缺少tzone,因此不会执行此代码。在你的
第二次调用,tzone不是missing,因此它被执行。

如果您逐步浏览xts.R中的代码,则可以看到(如果tzonemissing中的Dates强制为aa$Date
index <- as.numeric(as.POSIXct(order.by))

我认为问题在于POSIXct的默认设置为as.Date.POSIXct,因此除非您指定其他名称,否则将使用该默认设置。
x <- structure(1290125760,
               tzone = structure("America/Chicago", .Names = "TZ"),
               tclass = c("POSIXt", "POSIXct"),
               class = c("POSIXct", "POSIXt"))
x
#[1] "2010-11-18 18:16:00 CST"
str(x)
#POSIXct[1:1], format: "2010-11-18 18:16:00"
as.Date(x)
#[1] "2010-11-19"
as.Date(x, origin=as.Date("1970-01-01"), tz="America/Chicago")
#[1] "2010-11-18"

10-08 07:57
查看更多