[英]Working With Weekly Time Series Data In R using xts
这是一个样本 dataframe,每周(星期六)观察一次数据。
dataframe 中有 104 个观测值
#52 是 2020 年的最后一次观察,#53 是 2021 年的第一次观察:
我试图分解它进行一年比一年的分析:
data <- read.csv ("sum_data.csv", header=TRUE, stringsAsFactors=FALSE)
data$date <- as.Date(data$date)
data_xts <- xts(data$total_encounters, data$date, start = (2020-01-04), frequency = 52)
head(data_xts)
index(data_xts)
periodicity(data_xts)
frequency(data_xts) #0.14 is wrong, S/B 2
nweeks(data_xts)
plot(data_xts, ylab = "dod_cli_encounters")
xts_data_decomp <- decompose(data_xts, type = "mult")
plot(xts_data_decomp)
但是,当我运行分解 function 时,出现以下错误:
时间序列没有或少于 2 个周期
我确实注意到频率 function 返回 0.1428,它应该是 2。我如何让 xts 知道这是一个每周数据集,应该这样处理?
这是输出:
data <-
structure(list(X = 1:104, date = structure(c(18265, 18272, 18279,
18286, 18293, 18300, 18307, 18314, 18321, 18328, 18335, 18342, 18349,
18356, 18363, 18370, 18377, 18384, 18391, 18398, 18405, 18412, 18419,
18426, 18433, 18440, 18447, 18454, 18461, 18468, 18475, 18482, 18489,
18496, 18503, 18510, 18517, 18524, 18531, 18538, 18545, 18552, 18559,
18566, 18573, 18580, 18587, 18594, 18601, 18608, 18615, 18622, 18629,
18636, 18643, 18650, 18657, 18664, 18671, 18678, 18685, 18692, 18699,
18706, 18713, 18720, 18727, 18734, 18741, 18748, 18755, 18762, 18769,
18776, 18783, 18790, 18797, 18804, 18811, 18818, 18825, 18832, 18839,
18846, 18853, 18860, 18867, 18874, 18881, 18888, 18895, 18902, 18909,
18916, 18923, 18930, 18937, 18944, 18951, 18958, 18965, 18972, 18979,
18986), class = "Date"), total_encounters = c(287906L, 549315L,
520135L, 448754L, 535075L, 529320L, 501597L, 437590L, 535149L,
533067L, 515730L, 483225L, 401350L, 348270L, 299971L, 276799L,
277489L, 289127L, 305620L, 320805L, 323691L, 298987L, 377737L,
385446L, 399777L, 412889L, 328152L, 413512L, 428903L, 439043L,
419405L, 426545L, 434972L, 432648L, 441663L, 416962L, 374311L,
450942L, 461086L, 473937L, 462994L, 416820L, 502248L, 486632L,
493260L, 415058L, 522538L, 325256L, 516749L, 498325L, 487383L,
263927L, 275647L, 525448L, 523922L, 444946L, 538128L, 545296L,
507652L, 401458L, 566012L, 555483L, 543088L, 523277L, 553983L,
528812L, 520043L, 524375L, 518190L, 501871L, 504872L, 508024L,
505778L, 457917L, 399435L, 482569L, 450510L, 455820L, 425968L,
365471L, 459818L, 464688L, 466636L, 473430L, 479059L, 478048L,
495112L, 471965L, 416111L, 494969L, 490780L, 488221L, 477747L,
419577L, 501869L, 498140L, 486291L, 399430L, 508608L, 305376L,
509681L, 486055L, 466249L, 298166L)), row.names = c(NA,
-104L), class = "data.frame")
decompose 要求一个完整的周期必须表示为 1 个单位,而 Date class 将 1 天表示为 1 个单位,因此要有一年,因为与 decompose xts 一起使用的周期不适用。 请改用 ts。 假设数据从一年的第一周开始,每年有 52 周,我们有以下内容。
library(zoo)
z <- read.zoo(data[-1])
tt <- ts(z, start = as.yearmon(start(z)), freq = 52)
tt.d <- decompose(tt)
library(xts)
x <- as.xts(z)
对于绘图 plot(tt)、plot(z) 和 plot(x) 都有效。 我们显示对应于以下代码的图。
plot(tt)
plot(tt.d)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.