[R] Matching vector order by indicators in a matrix

Marc Schwartz marc_schwartz at me.com
Fri Jun 17 00:01:10 CEST 2011


On Jun 16, 2011, at 4:52 PM, Jeremy Beaulieu wrote:

> Hi all~
> 
> I have a bit of stupid question. And I promise, I have struggled through this and it sort of pains me to post this question... 
> 
> I have the following vector which is are the estimated parameter values output from "optim". 
> 
> $Rates
> [1] 0.006280048 0.330934659
> 
> I want to match the order in the vector by the number in the following matrix:
> 
> $Index.matrix
> 
> ALPHA    1 1
> BETA       2 2
> 
> In other words, the first value in $Rates should go wherever there is a "1" in the $Index.matrix. And the second value should go wherever there is a "2", and so on. I have some pretty hacky solutions, but I wanted to see if there was an easy way to do this that I am completely missing.
> 
> Thanks and all the best,
> 
> Jeremy


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


If you want to overwrite Index.Matrix:

Index.Matrix[] <- Rates[Index.Matrix]

> Index.Matrix
            [,1]        [,2]
[1,] 0.006280048 0.006280048
[2,] 0.330934659 0.330934659


HTH,

Marc Schwartz



More information about the R-help mailing list