[R] update matrix with subset of it where only row names match

Martin Waller martinej.waller at ntlworld.com
Tue Nov 13 22:44:25 CET 2007


jim holtman wrote:
> Here is one way of doing it that uses the row and column names:
> 
>> # create test data
>> mat1 <- matrix(0, nrow=10, ncol=3)
>> dimnames(mat1) <- list(paste('row', 1:10, sep=''), LETTERS[1:3])
>> mat2 <- matrix(1:3, ncol=1, dimnames=list(c('row3', 'row7', 'row5'), "B"))
>> mat2
>      B
> row3 1
> row7 2
> row5 3
>> # create indexing matrix
>> indx <- cbind(match(rownames(mat2), rownames(mat1)), match(colnames(mat2), colnames(mat1)))
>> indx
>      [,1] [,2]
> [1,]    3    2
> [2,]    7    2
> [3,]    5    2
>> mat1[indx] <- mat2
>> mat1
>       A B C
> row1  0 0 0
> row2  0 0 0
> row3  0 1 0
> row4  0 0 0
> row5  0 3 0
> row6  0 0 0
> row7  0 2 0
> row8  0 0 0
> row9  0 0 0
> row10 0 0 0
> 
> 
> On Nov 12, 2007 4:54 PM, Martin Waller <martinej.waller at ntlworld.com> wrote:
<snip>

OK - I see that, and thanks for your response, but (and excuse my 
ignorance, less than 2 months in R...) can you help me to see why this 
is 'better' (whatever that means, if anything)?  From a newbie (at least 
my) POV, it seems less clear than my original solution. Again, please 
bear in mind I am relatively new so please be patient if I'm not seeing 
something that's obvious to yourself. I have a genuine desire to learn.

Martin



More information about the R-help mailing list