首页 > 解决方案 > 如何使用 R 中的“应用”为时间序列数据绘制 acf 函数

问题描述

我有时间序列数据。我想应用acf函数并绘制所有列的结果。我还想让情节自动为每个单变量系列生成标题。

我尝试了以下方法:

library(quantmod)
library(TSclust)
library(ggplot2)
library(tsibble)
library(vcd)
## Prepare the data
symbols = c('AZN', 'BP', 'AAPL')

## Start and end time
start = as.Date("2015-01-05")
until = as.Date("2015-12-31")

stocks.Cl = lapply(symbols, function(symbol) {
  Close = getSymbols(symbol,src='yahoo', from = start, to = until, auto.assign = FALSE)[, 4]
  names(Close) = symbol
  Close
})
stocks.Cl = do.call(merge.xts,stocks.Cl)

acf.dat <- apply(stocks.Cl, MARGIN= 2, FUN = plot(acf))

但我得到以下信息:

Error in curve(expr = x, from = from, to = to, xlim = xlim, ylab = ylab,  : 
  'expr' did not evaluate to an object of length 'n'

标签: r

解决方案


您需要使用匿名函数将附加函数应用于传递的对象。而不是applywithMARGIN = 2我们使用lapply并遍历namesofstocks.Cl以用作情节的标题。

lapply(names(stocks.Cl), function(i) plot(acf(stocks.Cl[, i]), main = i))

推荐阅读