Avoiding loops to spare time and memory
Have you profiled your code (see `Writing R Extensions')? My guess is that most of the time is being spent in eigen(); if so you would have to use a different approach to gain much speed. BTW, please make more use of the space bar: your code is nigh unreadable (and so I've not tried to read it in detail). `Writing R Extensions' also shows you how to format code well.
On Thu, 8 May 2003, Dirk Enzmann wrote:
Is it possible to avoid the loop in the following function (or make the
function otherwise more efficient) and can someone point me to a
possible solution? (It would be great if hours could be reduced to
seconds :-).
# ---------------------------------------------
RanEigen=function(items=x,cases=y,sample=z)
{
X=matrix(rnorm(cases*items),nrow=cases,byrow=F)
S=crossprod(X-rep(1,cases) %*% t(colMeans(X)))
EV=eigen((1/sqrt(diag(S))*diag(items))%*%S%*%(1/sqrt(diag(S))*diag(items)),only.values=T)$values
for (i in 2:sample)
{
X=matrix(rnorm(cases*items),nrow=cases,byrow=F)
S=crossprod(X-rep(1,cases) %*% t(colMeans(X)))
EV=rbind(EV,eigen((1/sqrt(diag(S))*diag(items))%*%S%*%(1/sqrt(diag(S))*diag(items)),only.values=T)$values)
}
REigV=(cbind(1:items,colMeans(EV)))
REigV[,2]=as.numeric(formatC(REigV[,2],format="f",digits=7,flag="
",width=10))
colnames(REigV)=c(' ','Eigenvalue')
rownames(REigV)=rep('',items)
return(REigV)
}
# ---------------------------------------------
Brian D. Ripley, ripley at stats.ox.ac.uk Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UK Fax: +44 1865 272595