Break square matrix into pairs
-
30-03-2021 - |
Question
I have a large square matrix 12128 x 12128
. Example
A B C D E
A 0.5 0.4 0.1 0.02 0.4
B 0.1 0.3 0.07 0.03 0.9
C 0.8 0.04 0.5 0.4 0.4
D 3.4 5.6 9.5 2 2.1
E 0.6 9.1 0.3 0.5 1.2
I have a list of pairs (# 18000), which exist in all the possible pairs from the matrix
A B
B E
C E
I need the values for only the pairs in my list from the matrix. Is there a easier way to do it rather than breaking down the whole matrix (melt(matrix)
)? Thanks
Solution
Using m
and ind
from the other post as test data try this:
m[ind]
EDIT:
If the row and column names can have duplicates (as suggested in a later comment) and if we want all possible values from these then try this:
merge(as.data.frame.table(m), ind, by = 1:2)
OTHER TIPS
I make no promises about the performance characteristics of this method, since you actual data is fairly large, but this may at least give you the necessary tools to work with:
#Some example data like yours
m <- matrix(1:25,5,5)
rownames(m) <- letters[1:5]
colnames(m) <- letters[1:5]
#Matrix of row/col indices to select
ind <- cbind(c('a','e','b'),c('d','a','d'))
#Select elements of m matching ind
diag(m[match(ind[,1],rownames(m)),match(ind[,2],colnames(m))])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow