2014-11-03 82 views
3

我目前使用以下方法執行樣式分析:http://www.r-bloggers.com/style-analysis/。在36個月的滾動窗口中,這是一系列基準中一項資產的有限迴歸。使用for循環執行多次迴歸

我的問題是,我需要對相當多的資產執行此迴歸,並且逐個執行該操作會花費大量時間。更確切地說:有沒有辦法告訴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) 

非常感謝您的任何提示!

回答

2

「有沒有辦法告訴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]]