0

This post sort of gets to my question :Linear Regression loop for each independent variable individually against dependent

However, I am trying too add rolling periods for the regression.

Example:

data <-data.frame("col1"=runif(10,2,10),"col2"=runif(10,1,10),"col3"=runif(10,1,10),"col4"=runif(10,1,10))

sapply(data, function(x) rollapply(data,30, coef(lm(data$col1~x,data=data))))

EDIT: To give an deeper idea of what I am after, I should note that prior to using the Sapply method (after having read some SO posts that vectorized solutions were preferred), I had been trying for loops to loop over the columns I wanted to use as independent variables.

betadf <- data.frame()
for (i in colnames(data2[,3:ncol(data2)])){
formula <- formula(paste("variablename ~",i,sep=""))
data3 <- na.omit(merge(data2[,'variablename'],data2[,i]))
model <- na.omit(rollapply(data3,rollperiod, 
                         function(z) coef(lm(formula,data=as.data.frame(z))),
                         by.column = FALSE, align = "right"))
colnames(model) <- c("intercept",i)
betadf <- cbind(betadf,model[,i])
}
Community
  • 1
  • 1
user2662565
  • 509
  • 2
  • 9
  • 22
  • what package is `rollapply` in? – alexwhitworth Oct 01 '15 at 17:10
  • zoo, sorry didn't realize it was a zoo-specific question – user2662565 Oct 01 '15 at 17:12
  • I don't think this is [reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). You have only 10 obs but trying to roll over 30 periods (which don't exist). – alexwhitworth Oct 01 '15 at 18:01
  • 1
    Also, from a statistical perspective, I assume this is some sort of time series regression. But you're using `lm`. IE- you have `lm` on data with correlated errors, which is very, very wrong. – alexwhitworth Oct 01 '15 at 18:02
  • So my series has 3000 periods, and I have 150 variables (columns). I basically want the rolling 30-day coefficient for each of the variables. Not sure if correlated errors is an issue here but definitely worth looking into, you're right. – user2662565 Oct 01 '15 at 20:14

0 Answers0