创建一个 ts 对象
时间序列数据可以存储为 ts
对象。ts
对象包含有关 ARIMA 函数使用的季节性频率的信息。它还允许使用 window
命令按日期调用系列中的元素。
#Create a dummy dataset of 100 observations
x <- rnorm(100)
#Convert this vector to a ts object with 100 annual observations
x <- ts(x, start = c(1900), freq = 1)
#Convert this vector to a ts object with 100 monthly observations starting in July
x <- ts(x, start = c(1900, 7), freq = 12)
#Alternatively, the starting observation can be a number:
x <- ts(x, start = 1900.5, freq = 12)
#Convert this vector to a ts object with 100 daily observations and weekly frequency starting in the first week of 1900
x <- ts(x, start = c(1900, 1), freq = 7)
#The default plot for a ts object is a line plot
plot(x)
#The window function can call elements or sets of elements by date
#Call the first 4 weeks of 1900
window(x, start = c(1900, 1), end = (1900, 4))
#Call only the 10th week in 1900
window(x, start = c(1900, 10), end = (1900, 10))
#Call all weeks including and after the 10th week of 1900
window(x, start = c(1900, 10))
可以使用多个系列创建 ts
对象:
#Create a dummy matrix of 3 series with 100 observations each
x <- cbind(rnorm(100), rnorm(100), rnorm(100))
#Create a multi-series ts with annual observation starting in 1900
x <- ts(x, start = 1900, freq = 1)
#R will draw a plot for each series in the object
plot(x)