Skip to content
Prev 205670 / 398506 Next

faster GLS code

Try this:


X <- kronecker(diag(1,3),x)
Y <- c(y) # stack the y in a vector

# residual covariance matrix for each observation
covar <- kronecker(sigma,diag(1,N))

csig <- chol2inv(covar)
betam2 <- ginv(csig %*% X) %*% csig %*% Y

This is more than 2 times faster than your code (however, it doesn't compute `betav') . 

Here is a timing comparison:

# Your method
# GLS betas covariance matrix
system.time({
inv.sigma <- solve(covar)
betav <- solve(t(X)%*%inv.sigma%*%X)

# GLS mean parameter estimates
betam <- betav%*%t(X)%*%inv.sigma%*%Y
})

# New method
system.time({
csig <- chol2inv(covar)
betam2 <- ginv(csig %*% X) %*% csig %*% Y
})

all.equal(betam, betam2)
+ inv.sigma <- solve(covar)
+ betav <- solve(t(X)%*%inv.sigma%*%X)
+ 
+ # GLS mean parameter estimates
+ betam <- betav%*%t(X)%*%inv.sigma%*%Y
+ })
   user  system elapsed 
   1.14    0.51    1.76
+ csig <- chol2inv(covar)
+ betam2 <- ginv(csig %*% X) %*% csig %*% Y
+ })
   user  system elapsed 
   0.47    0.08    0.61
[1] TRUE
Hope this helps,
Ravi.
____________________________________________________________________

Ravi Varadhan, Ph.D.
Assistant Professor,
Division of Geriatric Medicine and Gerontology
School of Medicine
Johns Hopkins University

Ph. (410) 502-2619
email: rvaradhan at jhmi.edu


----- Original Message -----
From: Carlo Fezzi <c.fezzi at uea.ac.uk>
Date: Thursday, January 7, 2010 12:13 pm
Subject: [R] faster GLS code
To: r-help at r-project.org