Matching vector order by indicators in a matrix
Folks: This is sufficiently "tricky" that a word of explanation might be helpful to reveal the magic.
Rates <- c(0.006280048, 0.330934659) Index.Matrix <- matrix(c(1, 2, 1, 2), 2, 2)
Rates
[1] 0.006280048 0.330934659
Index.Matrix
? ? [,1] [,2] [1,] ? ?1 ? ?1 [2,] ? ?2 ? ?2 Just index 'Rates' by the values in Index.Matrix:
Rates[Index.Matrix]
[1] 0.006280048 0.330934659 0.006280048 0.330934659 NewMatrix <- matrix(Rates[Index.Matrix], dim(Index.Matrix))
NewMatrix
? ? ? ? ? ?[,1] ? ? ? ?[,2] [1,] 0.006280048 0.006280048 [2,] 0.330934659 0.330934659
The key here is to understand that matrices (arrays of any dimension actually) are just vectors stored in column major order (column 1 on top of column 2 ....) . So Rates[Index.Matrix] is just a length 4 vector concatenating two copies of Rates when you think of Index.matrix as a vector, which it must be here to index a vector (There's also matrix indexing of arrays, but that's something else again). The matrix() function then just makes it a matrix with the desired dimension. So no longer tricky, right? Cheers, Bert Bert Gunter Genentech