Depending upon the size of the matrix, using:
diag(cov(t(x), t(y)))
might be notably faster. On smaller matrices the time savings is
negligible.
Using Jorge's example below:
> diag(cov(t(X), t(Y)))
[1] 0.23396819 0.51455839 1.13851842 -4.30551345 -2.60720372
[6] -0.06834326 0.78344182 -0.02085422 1.05896045 1.37631451
HTH,
Marc Schwartz
On Apr 19, 2009, at 12:22 PM, Jorge Ivan Velez wrote:
Dear Benny,
Here is something that could get you a hint:
# Some data
set.seed(123)
X <- matrix(rnorm(100),ncol=10)
Y <- matrix(rnorm(100,2,4),ncol=10)
# Number of rows
n<-nrow(X)
# Covariances
sapply(1:n,function(i) cov(X[i,],Y[i,]))
# [1] 0.23396819 0.51455839 1.13851842 -4.30551345 -2.60720372
-0.06834326 0.78344182 -0.02085422
# [9] 1.05896045 1.37631451
See ?cov and ?sapply for more details.
HTH,
Jorge
On Sun, Apr 19, 2009 at 1:12 PM, Benny Chain <b.ch...@ucl.ac.uk>
wrote:
Does anyone know a way to calculate the covariances between two
arrays/matrices x and y, row by row. i.e. var(x[n,],y[n,]) for all
n ?
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.