[R] Rollapply

Pete B Peter.Brecknock at bp.com
Wed Jan 13 21:45:39 CET 2010


Hi 

I would like to understand how to extend the function (FUN) I am using in
rollapply below.

######################################
With the following simplified data, test1 yields parameters for a rolling
regression

data = data.frame(Xvar=c(70.67,70.54,69.87,69.51,70.69,72.66,72.65,73.36),
               Yvar =c(78.01,77.07,77.35,76.72,77.49,78.70,77.78,79.58))
data.z = zoo(d)

test1 = rollapply(data.z, width=3, 
          FUN = function(z) coef(lm(z[,1]~z[,2], 
          data=as.data.frame(z))), by.column = FALSE, align = "right")

print(test1)

######################################

Rewriting this to call myfn1 gives test2 (and is consistent with test1
above)

myfn1 = function(mydata){
      dd = as.data.frame(mydata) 
      l = lm(dd[,1]~dd[,2], data=dd)
      c = coef(l)
    }

test2 = rollapply(data.z, width=3, 
     FUN= myfn1, by.column = FALSE, align = "right")

print(test2)

######################################

I would like to be able to use the predict function to obtain a prediction
(and its std error) from the rolling regression I have just calculated.

My effort below issues a warning that 'newdata' had 1 row but variable(s)
found have 3 rows.
(if I run this outside of rollapply I don't get this warning) 

Also, I don't see the predicted value or its se with print(fm2[[1]]). Again,
if I run this outside of rollapply I am able to extract the predicted value.


Xpred=c(70.67)

myfn2 = function(mydata){
      dd = as.data.frame(mydata) 
      l = lm(dd[,1]~dd[,2], data=dd)
      c = coef(l)
      p = predict(l, data.frame(Xvar=Xpred),se=T)
      ret=c(l,c,p)
    }

fm2 = rollapply(data.z, width=3, 
     FUN= myfn2, by.column = FALSE, align = "right")

print(fm2[[1]])


Any insights would be gratefully received.

Best regards

Pete
-- 
View this message in context: http://n4.nabble.com/Rollapply-tp1013345p1013345.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list