我正在使用时间序列数据并遇到apply.weekly()
的问题。似乎在某个特定日期之后,几周内没有正确聚合。
library(xts)
value <- c(46.40269, 47.27100 ,47.73311, 46.12858, 44.54989 ,42.79287, 41.70017 ,41.22373, 40.16180, 38.48705 ,37.02111 ,35.95312, 37.47187, 42.59649 ,49.22880, 53.96820, 57.97346, 61.22755,61.79824, 65.05720, 65.30233 ,61.86191,58.03687, 55.17815, 52.88933, 51.47876, 50.31402, 48.91674, 47.47042)
DATE <- as.Date(c("2038-01-03", "2038-01-04", "2038-01-05", "2038-01-06", "2038-01-07" ,"2038-01-08", "2038-01-09", "2038-01-10", "2038-01-11", "2038-01-12", "2038-01-13" ,"2038-01-14", "2038-01-15" ,"2038-01-16" ,"2038-01-17", "2038-01-18", "2038-01-19", "2038-01-20", "2038-01-21", "2038-01-22", "2038-01-23", "2038-01-24" ,"2038-01-25", "2038-01-26", "2038-01-27", "2038-01-28", "2038-01-29", "2038-01-30", "2038-01-31"))
DF <- data.frame(DATE, value)
DF_daily <- xts(DF$value, order.by = DF$DATE)
DF_weekly <- apply.weekly(DF_daily, FUN=sum)
print(DF_weekly)
这会生成以下输出:
[,1]
2038-01-03 46.40269
2038-01-10 311.39935
2038-01-16 231.69144
2038-01-31 840.70198
注意最后一段时间是15天。现在,如果我改用2010年的日期,我会得到你所期望的。也就是说,使用
DATE <- as.Date(c("2010-01-03", "2010-01-04", "2010-01-05", "2010-01-06", "2010-01-07" ,"2010-01-08" ,"2010-01-09" ,"2010-01-10", "2010-01-11", "2010-01-12" ,"2010-01-13" ,"2010-01-14" ,"2010-01-15" ,"2010-01-16", "2010-01-17", "2010-01-18", "2010-01-19" ,"2010-01-20" ,"2010-01-21" ,"2010-01-22", "2010-01-23", "2010-01-24", "2010-01-25" ,"2010-01-26","2010-01-27" ,"2010-01-28" ,"2010-01-29" ,"2010-01-30", "2010-01-31"))
在上面的代码中生成输出:
[,1]
2010-01-03 46.40269
2010-01-10 311.39935
2010-01-17 280.92024
2010-01-24 427.18889
2010-01-31 364.28429
2038年我不知道有什么奇怪的事吗?
我在64位Windows 7企业版上运行此代码,sessionInfo()
返回以下输出
R version 3.2.3 (2015-12-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
locale:
[1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C LC_TIME=English_United States.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] xts_0.9-7 zoo_1.7-12
loaded via a namespace (and not attached):
[1] tools_3.2.3 grid_3.2.3 lattice_0.20-33
答案 0 :(得分:0)
2038年1月19日是一个特殊日期:凌晨3:14:08,一个32位的unix时期(计算自1970年1月1日午夜以来的秒数)将会溢出。处理时间戳可能存在导致此日期计数器中断的错误。许多数字存储为带符号的32位整数,其最大值为2,147,483,647。
这被称为"Year 2038 Problem",类似于Y2K问题。
但是,R Date
type is in the number of days, instead of the number of seconds,自Unix Epoch以来。对我而言,这表明xts
包存在问题。
在这个问题上你并不孤单(here is a 2012 discussion on a mailing list),并且看起来这个错误来自于系统日期处理和R日期处理之间的错误切换。