【问题标题】:Using a for loop for performing several regressions使用 for 循环执行多个回归
【发布时间】:2014-12-30 14:56:06
【问题描述】:

我目前正在使用以下方法进行样式分析:http://www.r-bloggers.com/style-analysis/。它是一项资产在 36 个月滚动窗口内在多个基准上的受限回归。

我的问题是我需要对相当多的资产执行此回归,并且逐个执行此操作将花费大量时间。更准确地说:有没有办法告诉 R 在第 101-116 列上逐一回归第 1-100 列。当然,这也意味着要打印 100 个不同的图,每个资产一个。我是 R 新手,现在已经卡了好几天了。

我希望以下摘录不可重现并不重要,因为代码按最初的预期工作。

# Style Regression over Window, constrained
#--------------------------------------------------------------------------
# setup
load.packages('quadprog')

style.weights[] = NA
style.r.squared[] = NA

# Setup constraints
# 0 <= x.i <= 1
constraints = new.constraints(n, lb = 0, ub = 1)

# SUM x.i = 1
constraints = add.constraints(rep(1, n), 1, type = '=', constraints)        

# main loop
for( i in window.len:ndates ) {
    window.index = (i - window.len + 1) : i

fit = lm.constraint( hist.returns[window.index, -1], hist.returns[window.index, 1], constraints )   
    style.weights[i,] = fit$coefficients
    style.r.squared[i,] = fit$r.squared
}

# plot  
aa.style.summary.plot('Style Constrained', style.weights, style.r.squared, window.len)

非常感谢您提供的任何提示!

【问题讨论】:

    标签: r loops for-loop regression


    【解决方案1】:

    “有没有办法告诉 R 在 101-116 列上逐列回归 1-100 列。”

    是的!您可以使用 for 循环,但您还有一系列合适的“应用”函数。这是一个带有随机/玩具数据集并使用lm() 的通用解决方案,但您可以加入任何您想要的回归函数

    # data frame of 116 cols of 20 rows
    set.seed(123)
    dat <- as.data.frame(matrix(rnorm(116*20), ncol=116))
    
    # with a for loop
    models <- list() # empty list to store models
    
    for (i in 1:100) {
      models[[i]] <-
        lm(formula=x~., data=data.frame(x=dat[, i], dat[, 101:116]))
    }
    
    # with lapply
    models2 <-
      lapply(1:100, 
             function(i) lm(formula=x~., 
                            data=data.frame(x=dat[, i], dat[, 101:116])))
    
    # compare. they give the same results!
    all.equal(models, models2)
    
    # to access a single model, use [[#]]
    models2[[1]]
    

    【讨论】:

      猜你喜欢
      • 2021-02-18
      • 1970-01-01
      • 1970-01-01
      • 2015-12-27
      • 2015-02-10
      • 1970-01-01
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多