3
我有13個矩陣的各種尺寸,我想用於與自定義函數(計算Rv係數)的成對矩陣相關性。該函數接受兩個參數(matrix1,matrix2)並生成一個標量(基本上是一個多變量r值)。我想在所有可能的矩陣對上運行函數(所以總共有78個相關),並生成一個13乘13矩陣的結果Rv值和行和列中13個矩陣的名稱。我想通過將matricies放在一個列表中,並使用double for循環遍歷列表中的元素來實現這一點,但這似乎非常複雜。我已經在下面給出了一個假數據的例子。有沒有人有任何建議如何接近?提前致謝。R中的成對矩陣相關 - 如何遍歷所有對?
# 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?
你的'psd'函數已經實現爲'tcrossprod'(並且效率更高)。 – Marek 2010-10-27 15:35:51