R语言开发之时间序列分析了解下

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/luyaran/article/details/82782577

时间序列是一系列数据点,其每个数据点与时间戳相关联。 一个简单的例子就是股票在某一天不同时间点的股票价格,另一个例子是一年中不同月份某个地区的降雨量。

R语言使用许多功能来创建,操纵和绘制时间序列数据,并且这个时间序列的数据存储在称为时间序列对象的R对象中。 它也是一个R数据对象,如向量或数据帧。

在R中时间序列对象是通过使用ts()函数创建的,语法如下:

timeseries.object.name <-  ts(data, start, end, frequency)

参数描述如下:

  • data - 是包含时间序列中使用的值的向量或矩阵。
  • start - 以时间序列指定第一次观察的开始时间。
  • end - 指定时间序列中最后观察的结束时间。
  • frequency - 指定每单位时间的观测次数。

上述参数除了data参数之外,其他参数全是可选项。

接下来,我们就来做一个假设,来逐步分析下。

假设从2012年1月开始,我们需要表述某地的年降雨统计信息。那我们就来创建一个R时间序列对象,为期12个月,并绘制,如下:

setwd("D:/r_file")

# 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

产生的图片如下:

上述实例中的ts()函数中的频率(frequency)参数的值决定了测量数据点的时间间隔,它的值为12表示时间序列为12个月,具体参数描述如下:

  • frequency= 12 - 每一个月的数据点。
  • frequency= 4 - 每年四分之一的数据点。
  • frequency= 6 - 每一小时10分钟的数据点。
  • frequency= 24 6* - 每天10分钟的数据点。

最后我们来尝试在一个图表中绘制多个时间序列,将这两个系列组合成一个矩阵,如下:

setwd("D:/r_file")
# 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()

输出结果如下:

           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

产生的图片如下:

好啦,本次记录就到这里了。

如果感觉不错的话,请多多点赞支持哦。。。

猜你喜欢

转载自blog.csdn.net/luyaran/article/details/82782577