時間序列是一系列數(shù)據(jù)點,其每個數(shù)據(jù)點與時間戳相關(guān)聯(lián)。 一個簡單的例子就是股票在某一天不同時間點的股票價格。另一個例子是一年中不同月份某個地區(qū)的降雨量。R語言使用許多功能來創(chuàng)建,操縱和繪制時間序列數(shù)據(jù)。時間序列的數(shù)據(jù)存儲在稱為時間序列對象的R對象中。 它也是一個R數(shù)據(jù)對象,如向量或數(shù)據(jù)幀。
時間序列對象是通過使用ts()函數(shù)創(chuàng)建的。
時間序列分析所使用的ts()函數(shù)的基本語法是 -
timeseries.object.name <- ts(data, start, end, frequency)
以下是使用的參數(shù)的描述 -
除參數(shù)“data”外,所有其他參數(shù)均為可選項。
假設(shè)從2012年1月開始,要表述某地的年降雨統(tǒng)計信息。我們創(chuàng)建一個R時間序列對象,為期12個月,并繪制。
setwd("F:/worksp/R")
# Get the data points in form of a R vector.
rainfall <- c(799,1174.8,865.1,1334.6,635.4,918.5,685.5,998.6,784.2,985,882.8,1071)
# Convert it to a time series object.
rainfall.timeseries <- ts(rainfall,start = c(2012,1),frequency = 12)
# Print the timeseries data.
print(rainfall.timeseries)
# Give the chart file a name.
png(file = "rainfall.png")
# Plot a graph of the time series.
plot(rainfall.timeseries)
# Save the file.
dev.off()
當(dāng)我們執(zhí)行上面的代碼,它產(chǎn)生以下結(jié)果和圖表 -
Jan Feb Mar Apr May Jun Jul Aug Sep
2012 799.0 1174.8 865.1 1334.6 635.4 918.5 685.5 998.6 784.2
Oct Nov Dec
2012 985.0 882.8 1071.0
降雨量的時間序列圖 -

ts()函數(shù)中的頻率(frequency)參數(shù)的值決定了測量數(shù)據(jù)點的時間間隔。 值為12表示時間序列為12個月。其他值及其含義如下 -
我們可以在一個圖表中繪制多個時間序列,將這兩個系列組合成一個矩陣。
setwd("F:/worksp/R")
# Get the data points in form of a R vector.
rainfall1 <- c(799,1174.8,865.1,1334.6,635.4,918.5,685.5,998.6,784.2,985,882.8,1071)
rainfall2 <-
c(655,1306.9,1323.4,1172.2,562.2,824,822.4,1265.5,799.6,1105.6,1106.7,1337.8)
# Convert them to a matrix.
combined.rainfall <- matrix(c(rainfall1,rainfall2),nrow = 12)
# Convert it to a time series object.
rainfall.timeseries <- ts(combined.rainfall,start = c(2012,1),frequency = 12)
# Print the timeseries data.
print(rainfall.timeseries)
# Give the chart file a name.
png(file = "rainfall_combined.png")
# Plot a graph of the time series.
plot(rainfall.timeseries, main = "多時間系列圖")
# Save the file.
dev.off()
當(dāng)我們執(zhí)行上面的代碼,它產(chǎn)生以下結(jié)果和圖表 -
Series 1 Series 2
Jan 2012 799.0 655.0
Feb 2012 1174.8 1306.9
Mar 2012 865.1 1323.4
Apr 2012 1334.6 1172.2
May 2012 635.4 562.2
Jun 2012 918.5 824.0
Jul 2012 685.5 822.4
Aug 2012 998.6 1265.5
Sep 2012 784.2 799.6
Oct 2012 985.0 1105.6
Nov 2012 882.8 1106.7
Dec 2012 1071.0 1337.8
多時間系列圖 -
