2017-08-29 66 views
2

我試圖rollapply做兩列在數據幀R:兩個變量

library(xts) 
library("dLagM") 

data(warming) 
fdlm1 <- function(){ 
model.ardl = ardlDlm(x = warming$NoMotorVehicles, y = warming$Warming, p = 1 , q = 1 , show.summary = FALSE) 

fc <- ardlDlmForecast(model = model.ardl , x = tail(x,1) , h =1)$forecasts 
fc 
return(fc)} 

dcalc1 <- rollapply(warming,18,fdlm1) 

rollapply不過是得到一個錯誤:

Error in FUN(data[posns], ...) : unused argument (data[posns]) 

感謝您指出任何幫助什麼我做錯了。

回答

3

默認情況下,rollapply單獨調用每個數據列的功能。如果您希望該功能可以訪問多個列,則需要設置by.column = FALSE

dcalc1 <- rollapply(warming, 18, fdlm1, by.column = FALSE) 

這個簡單的例子工程:

data(sample_matrix) 
x <- as.xts(sample_matrix) 
r <- rollapply(x, 40, function(d) coef(lm(Close ~ Open, data=d)), by.column=FALSE) 

如果你還有問題的話,我會解決的兩個問題,我與你的功能看:

  1. 你應該傳遞對象通過參數而不是 依靠範圍尋找它們,
  2. x in tail(x, 1)未在函數範圍中定義...因此很難說R在哪裏找到x的值。
+0

謝謝。我這樣做,但我仍然得到錯誤: –

+1

然後問題可能與您的函數,因爲一個簡單的例子工作:'數據(sample_matrix); x < - as.xts(sample_matrix); (x,40,函數(d)coef(lm(Close〜Open,data = d)),by.column = FALSE)。你真的應該通過參數傳遞對象到你的函數,而不是依靠範圍來找到它們。而'tail(x,1)'中的'x'沒有在函數範圍中定義...所以很難說R在哪裏找到'x'的值。 –

+0

感謝您的解釋。 –