这篇文章提到了我的问题:Linear Regression loop for each independent variable individually against dependent
但是,我正在尝试为回归添加滚动周期。
示例:
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))))
编辑:为了更深入地了解我所追求的内容,我应该注意在使用Sapply方法之前(在阅读了一些SO帖子之后,首选的矢量化解决方案),我一直在尝试循环遍历列我想用作自变量。
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])
}