脉冲响应函数的功能

Chr*_*her 9 r function

我创建了以下示例代码,以便在[vars][1]包的帮助下在R中绘制"脉冲响应函数" .

library(vars)
data(Canada)
Canada <- data.frame(Canada)

irfplot = function(x, y) {
  VAR <- VAR(cbind(x,y), p = 2, type = "trend")
  irf_o <-irf(VAR, impulse = colnames(VAR$y)[1], response = colnames(VAR$y)[2], boot = TRUE, cumulative = FALSE, n.ahead = 20, ci = 0.90)
  plot(irf_o)
}

irfplot(Canada["rw"],Canada["U"])
Run Code Online (Sandbox Code Playgroud)

到目前为止应该有效.但是,通过编写函数来尝试使脚本更灵活

irfplot = function(x, y, lags, deter) {
      VAR <- VAR(cbind(x,y), p = lags, type = deter)
...

irfplot(Canada["rw"],Canada["U"], 2, "trend")
Run Code Online (Sandbox Code Playgroud)

它返回:

Error in VAR(y = ysampled, p = lags, type = "trend") : 
  object 'lags' not found 
Run Code Online (Sandbox Code Playgroud)

问题:如何解决问题?我有一些其他函数通过对象传递值,但由于任何原因,它不起作用.

谢谢.

Man*_*l R 2

问题

问题是boot = TRUE函数的参数irf()。首先请注意,以下工作正常

irfplot <- function(x, y, lags, deter) {

  var_o   <- VAR(cbind(x, y), p = lags, type = deter)
  irf_o <- irf(var_o, 
               impulse = colnames(var_o$y)[1], 
               response = colnames(var_o$y)[2], boot = FALSE)
  plot(irf_o)
}
irfplot(Canada["rw"], Canada["U"], 3, "trend")
Run Code Online (Sandbox Code Playgroud)

更改boot为TRUE会导致错误。发生的情况是lags,deter显然没有正确传递给执行引导的函数。虽然,我不认为它在技术上是一个错误,但如果包的作者更改它肯定会有所帮助。

解决方案

每当您想要将顶级函数中的某些函数参数传递给某个较低级别的函数时,它不太容易出错(如您在示例中所见),并且通常建议使用该...参数。

irfplot <- function(x, y, ...) {

  var_o   <- VAR(cbind(x, y), ...)
  irf_o <- irf(var_o, 
               impulse = colnames(var_o$y)[1], 
               response = colnames(var_o$y)[2], boot = TRUE)
  plot(irf_o)
}
irfplot(Canada["rw"], Canada["U"], 3, "trend")
Run Code Online (Sandbox Code Playgroud)