R教程

R 时间序列分析

时间序列是一系列数据点,其中每个数据点都与时间戳相关联。一个简单的例子是股票市场在给定日期不同时间点的价格。另一个例子是一年中不同月份某个地区的降雨量。 R 语言使用许多函数来创建、操作和绘制时间序列数据。时间序列的数据存储在一个名为 time-series object 的 R 对象中。它也是一个类似于向量或数据框的 R 数据对象。
时间序列对象是使用 ts()函数创建的。

语法

时间序列分析中 ts() 函数的基本语法是-
timeseries.object.name <- ts(data, start, end, frequency)
以下是所用参数的说明-
data 是包含时间序列中使用的值的向量或矩阵。 start 指定时间序列中第一个观察的开始时间。 end 指定时间序列中最后一次观察的结束时间。 频率指定单位时间内的观察次数。
除参数"data"外,所有其他参数都是可选的。

示例

考虑从 2012 年 1 月开始的某个地点的年降雨量详细信息。我们创建了一个为期 12 个月的 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()
当我们执行上面的代码时,它会产生以下结果和图表-
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
时间序列图表-
使用 R 的时间序列

不同的时间间隔

ts() 函数中 frequency 参数的值决定了测量数据点的时间间隔。值为 12 表示时间序列为 12 个月。其他值及其含义如下-
频率 = 12 固定一年中每个月的数据点。 频率 = 4 与一年中每个季度的数据点挂钩。 频率 = 6 盯住一个小时每 10 分钟的数据点。 频率 = 24*6 将一天中每 10 分钟的数据点挂钩。

多个时间序列

我们可以通过将两个系列组合成一个矩阵,在一张图表中绘制多个时间序列。
# 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 = "Multiple Time Series")
# Save the file.
dev.off()
当我们执行上面的代码时,它会产生以下结果和图表-
           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
多时间序列图表-
Combined Time series is using R
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4