R でループを回避しようとしていますが、何度か使用する必要があるようです。
X=rnorm(100)
Y=matrix(rnorm(200*100),ncol=100)
Beta=function(y,period){ # y is a vector, maybe one row of Y
num.col=length(y)-period+1
ret=matrix(NA,1,num.col) # store the result
for(i in period:(length(y))){
lm.sol=lm(y[(i-period+1):i]~X[(i-period+1):i])
ret[i-period+1]=lm.sol$coefficients[2]
}
return(ret)
}
beta.30=apply(Y,1,Beta,period=30)
beta.30=t(beta.30)
を使用してループを回避しようとしましたが、関数にapply
まだループがあり、計算速度が十分に速くありません。このアルゴリズムでループを回避する方法はありますか? または、アルゴリズムを高速化する方法はありますか?for
Beta
for
ありがとう!
私が考えることができる1つの方法は、次のようにBeta
関数をコンパイルすることです:
require(compiler)
enableJIT(3)
しかし、まだ十分に高速ではありません。アルゴリズム自体を変更する必要があると思います。
lm.fit
役に立ちます!速度が大幅に向上します。
Beta1=function(y,period){
num.col=length(y)-period+1
ret=matrix(NA,1,num.col)
for(i in period:(length(y))){
A=matrix(c(rep(1,period),X[(i-period+1):i]),ncol=2)
lm.sol=lm.fit(A,y[(i-period+1):i])
ret[i-period+1]=lm.sol$coefficients[2]
}
return(ret)
}
system.time(apply(Y,1,Beta,period=30))
user system elapsed
19.08 0.00 19.08
system.time(apply(Y,1,Beta1,period=30))
user system elapsed
1.09 0.00 1.09