Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用for循环执行多个回归_R_Loops_For Loop_Regression - Fatal编程技术网

使用for循环执行多个回归

使用for循环执行多个回归,r,loops,for-loop,regression,R,Loops,For Loop,Regression,我当前正在使用以下方法执行样式分析:。这是一种在36个月的滚动窗口内,一项资产在多个基准上的约束回归 我的问题是,我需要对相当多的资产执行此回归,并且逐个执行会花费大量时间。更准确地说:有没有办法让R在101-116柱上逐个回归1-100柱。当然,这也意味着打印100个不同的绘图,每个资源一个。我是个新手,已经被困了好几天了 我希望下面的摘录不可复制并不重要,因为代码按照最初的预期工作 # Style Regression over Window, constrained #----------

我当前正在使用以下方法执行样式分析:。这是一种在36个月的滚动窗口内,一项资产在多个基准上的约束回归

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

我希望下面的摘录不可复制并不重要,因为代码按照最初的预期工作

# 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)
#窗口上的样式回归,受约束
#--------------------------------------------------------------------------
#设置
load.packages('quadprog')
style.weights[]=NA
样式r.平方[]=NA
#设置约束
#0“有没有办法告诉R在柱101-116上逐个回归柱1-100。”

对!!您可以使用for循环,但也可以使用一系列适当的“apply”函数。这是一个使用随机/玩具数据集并使用
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]]
#20行116列的数据帧
种子集(123)
dat