1

I have written what I believe to be a semi-quick ols-regression function

ols32 <- function (y, x,Ridge=1.1) {
xrd<-crossprod(x)
xry<-crossprod(x, y)
diag(xrd)<-Ridge*diag(xrd)
solve(xrd,xry)
}

Now I want to apply this to the following

(vapply(1:la, function(J) 
ME %*% ols32((nza[,J]),(cbind(nzaf1[,J],nzaf2[,J],nza[,-J],MOMF)))
[(la+2):(2*la+1)],FUN.VALUE=0))

Where nza,nzaf1,nzaf2 and MOMF are 500x50 matrixes and la=50 and ME is a vector of length 50. So what I actually do is I do a regression but only use the beta-coefficients from MOMF which I multiply by ME.

nza.mat<-matrix(rnorm(500*200),ncol=200)
nza<-nza.mat[,1:50]
nzaf2<-nza.mat[,101:150]
MOMF<-nza.mat[,151:200]
nzaf1<-nza.mat[,51:100]
ME<-nza.mat[500,151:200]

Is there an imediate way of making things faster or do I need to use someting like RcppEigen? Tks P

So I came up with a slightly faster way of solving this by rewriting my ols-function so that it calculates the two crossproducts only once for a whole matrix. The new function looks like this:

ols.quick <- function (y, x, ME) {
 la<-dim(y)[2]
 XX.cross<-crossprod(x)
 XY.cross<-crossprod(x, y)
 diag(XX.cross)<-Ridge*diag(XX.cross)
 betas<-sapply(1:la, function(J){
 idx<-c((1:la)[-J],la+J,2*la+J,(3*la+1):(4*la)); 
 solve(XX.cross[idx,idx],XY.cross[idx,J])},simplify=T)
 ME%*%betas[(la+2):(2*la+1),]
}

where y=nza (500x50) and x=cbind(nza,nzaf1,nzaf2,MOMF) (500x200) This solves the problem about 3.5 times faster.

microbenchmark(ols.quick(nza,nza.mat,ME),
vapply(1:la, function(J) ME%*%ols32(nza[,J],(cbind(nzaf1[,J],nzaf2[,J],nza[,-J],MOMF)))
[(la+2): (lb+2)],FUN.VALUE=0))


min        lq    median        uq       max neval
66.30495  67.71903  68.57001  70.17742  77.80069   100
251.59395 255.43306 258.35041 262.85742 296.51313   100

I suppose I could gain some speed with parLapply from the parallel package but I havet looked into that yet.

  • You're asking us to optimize something without [reproducible data](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Thomas Apr 24 '14 at 10:52
  • Sorry about that, added data now for reproducibility. – user1187861 Apr 24 '14 at 14:38

0 Answers0