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

jim holtman jholtman at gmail.com
Tue Nov 13 01:54:23 CET 2007


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:
> I guess this has a simple solution:
>
> I have matrix 'mat1' which has row and column names, e.g.:
>
>        A       B       C
> row1    0       0       0
> row2    0       0       0
> ....
> rown    0       0       0
>
> I have a another matrix 'mat2', essentially a subset of 'mat1' where the
> rownames are all in 'mat1' e.g.:
>
>        B
> row3    5
> row8    6
> row54   7
>
>
> I want to insert the values of matrix mat2 for column B (in reality it
> could be some or all of column names A, B or C, etc.) (same name in both
> matrices if that matters - rownames of mat2 guaranteed to be in mat1)
> into matrix mat1 where the rownames match, so final desired result is:
>
> matrix mat1:
>        A       B       C
> row1    0       0       0
> row2    0       0       0
> row3    0       5       0
> ...
> row8    0       6       0
> ...
> row54   0       7       0
> ..
> rown    0       0       0
>
> My solution was (along the lines of):
>
> mat1[rownames(mat2)%in%rownames(mat1),"B"]=mat2[,"B"]
>
> Is there a better way? It doesn't 'feel' right?
>
> Thanks - hope I explained it right (its late and I had a little drink
> about an hour ago,etc....).
>
>
> Martin
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?



More information about the R-help mailing list