tags:

views:

49

answers:

1

I have 13 matrices of various dimensions that i'd like to use in pairwise matrix correlations with a custom function (that calculates the Rv coefficient). The function takes two arguments (matrix1, matrix2) and produces a scalar (basically a multivariate r value). I'd like to run the function on all possible pairs of matrices (so 78 correlations in total) and produce a 13 by 13 matrix of the resulting Rv values with the names of the 13 matricies in the rows and columns. I thought of trying to do this by putting the matricies inside a list and using a double for loop to go through the elements of the list, but that seems very complex. I've given a stipped down example with dummy data below. Does anyone have any suggestions for how this might be approached? Thanks in advance.

# Rv function  
Rv <- function(M1, M2) {  
    tr <- function(x) sum( diag(x) )   
    psd <- function(x) x %*% t(x)   
    AA <- psd(M1)  
    BB <- psd(M2)  
    num <- tr(AA %*% BB)  
    den <- sqrt( tr(AA %*% AA) * tr(BB %*% BB) )  
    Rv <- num / den  
    list(Rv=Rv, "Rv^2"=Rv^2)  
}  

# data in separate matricies  
matrix1 <- matrix(rnorm(100), 10, 10)  
matrix2 <- matrix(rnorm(100), 10, 10)  
# ... etc. up to matrix 13  

# or, in a list  
matrix1 <- list( matrix(rnorm(100), 10, 10) )  
rep(matrix1, 13) # note, the matrices are identical in this example   

# call Rv function  
Rv1 <- Rv(matrix1, matrix2)  
Rv1$Rv^2  

# loop through all 78 combinations?  
# store results in 13 by 13 matrix with matrix rownames and colnames?  
+1  A: 

What I used in the past is expand.grid() followed by apply(). Here is a simpler example using just 1:3 rather than 1:13.

R> work <- expand.grid(1:3,1:3)
R> work
  Var1 Var2
1    1    1
2    2    1
3    3    1
4    1    2
5    2    2
6    3    2
7    1    3
8    2    3
9    3    3
R> apply(work, 1, function(z) prod(z))
[1] 1 2 3 2 4 6 3 6 9
R> 

You obviously want a different worker function.

Dirk Eddelbuettel