2013-10-28 57 views
0

我今天花了整整一天的时间来解决这个问题..请帮助我。 尽管我只是写了一个非常简单的例子,但我的原始数据有大量的变量 - 约2,000。因此,为了运行回归,我需要选择某些变量。 我确实需要开发很多模型,所以我应该自动执行此过程。R代码:滚动回归逐步

  1. 我运行stepwie。
  2. 我不知道有多少变量是逐步选择的。
  3. 选择变量后,我运行滚动回归进行预测。

    library(car) 
    library(zoo) 
    # run regression 
    m <- lm(mpg~., data=mtcars) 
    
    # run stepwise 
    s<-step(m, direction="both") 
    
    # select variables 
    variable<- attr(s$terms,"term.labels") 
    b<-paste(dep,paste(s, collapse="+"),sep = "~") 
    
    rollapply(mtcars, width = 2, 
          FUN = function(z) coef(lm(b, data = as.data.frame(z))), 
          by.column = FALSE, align = "right") 
    

    #这里是我公司开发的自动模式..

    models2 <- lapply(1:11, function(x) { 
        dep<-names(mtcars)[x] 
        ind<-mtcars[-x] 
        w<-names(ind) 
        indep<-paste(dep,paste(w, collapse="+"),sep = "~") 
        m<-lm(indep,data=mtcars) 
        s<-step(m, direction="both") 
        b<-paste(dep,paste(s, collapse="+"),sep = "~") 
        rollapply(mtcars, width = 2, 
          FUN = function(z) coef(lm(b, data = as.data.frame(z))), 
          by.column = FALSE, align = "right")}) 
    

我想从滚动回归计算预测..

然而,这是很难成立对于自变量没有预先知道的数据帧。

There is a similar one here, but in this model independent variables are known already.

回答

0

你不需要知道自变量!如果您提供包含所有变量的data.frame,则predict函数将选择必需的变量。类似于你已经链接的帖子,你可以这样:

mtcars[,"int"] <- seq(nrow(mtcars)) # add variable used to choose newdata 
models2 <- lapply(1:11, function(x) { 
    dep <- names(mtcars)[x] 
    ind <- mtcars[-x] 
    w <- names(ind) 
    form <- paste(dep,paste(w, collapse="+"),sep = "~") 
    m <- lm(form, data=mtcars) 
    s <- step(m, direction="both", trace=0) # model selection (don't print trace) 
    b <- formula(s) # This is clearer than your version 
    rpl <- rollapply(mtcars, width = 20, # if you use width=2, your model will always be overdetermined 
      FUN = function(z) { 
      nextD <- max(z[,'int'])+1 # index of row for new data 
      fit <- lm(b, data = as.data.frame(z)) # fit the model 
      c(coef=coef(fit), # coefficients 
       predicted=predict(fit, newdata=mtcars[nextD,])) # predict using the next row 
      }, 
      by.column = FALSE, align = "right") 
    rpl 
}) 
+0

哦天啊..!有用!!你救了我的生命..我已经花了整整一天的时间..非常感谢你。 – user976856