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

Martin Waller martinej.waller at ntlworld.com
Mon Nov 12 22:54:51 CET 2007


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



More information about the R-help mailing list