時(shí)間序列是一系列數(shù)據(jù)點(diǎn),其每個(gè)數(shù)據(jù)點(diǎn)與時(shí)間戳相關(guān)聯(lián)。 一個(gè)簡(jiǎn)單的例子就是股票在某一天不同時(shí)間點(diǎn)的股票價(jià)格。另一個(gè)例子是一年中不同月份某個(gè)地區(qū)的降雨量。R語(yǔ)言使用許多功能來(lái)創(chuàng)建,操縱和繪制時(shí)間序列數(shù)據(jù)。時(shí)間序列的數(shù)據(jù)存儲(chǔ)在稱為時(shí)間序列對(duì)象的R對(duì)象中。 它也是一個(gè)R數(shù)據(jù)對(duì)象,如向量或數(shù)據(jù)幀。
時(shí)間序列對(duì)象是通過(guò)使用ts()函數(shù)創(chuàng)建的。
時(shí)間序列分析所使用的ts()函數(shù)的基本語(yǔ)法是 -
timeseries.object.name <- ts(data, start, end, frequency)
以下是使用的參數(shù)的描述 -
除參數(shù)“data”外,所有其他參數(shù)均為可選項(xiàng)。
假設(shè)從2012年1月開(kāi)始,要表述某地的年降雨統(tǒng)計(jì)信息。我們創(chuàng)建一個(gè)R時(shí)間序列對(duì)象,為期12個(gè)月,并繪制。
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
降雨量的時(shí)間序列圖 -

ts()函數(shù)中的頻率(frequency)參數(shù)的值決定了測(cè)量數(shù)據(jù)點(diǎn)的時(shí)間間隔。 值為12表示時(shí)間序列為12個(gè)月。其他值及其含義如下 -
我們可以在一個(gè)圖表中繪制多個(gè)時(shí)間序列,將這兩個(gè)系列組合成一個(gè)矩陣。
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 = "多時(shí)間系列圖")
# 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
多時(shí)間系列圖 -
