[R] R- merging two matrix

Milan Bouchet-Valat nalimilan at club.fr
Mon Sep 10 09:22:38 CEST 2012


Le dimanche 09 septembre 2012 à 19:29 -0500, Sridhar Iyer a écrit :
> Hi,
> 
> I have two matrices.  (same size, same number of rows,
> same names for the rows  - one has data in sorted
> order, another one master data in unsorted order. I need to
> combine both).
> 
> Rows names of Matrix A
> P, Q, R, S, T, U, V .......        (some order) - each row has 4 values
> 
> Row names of Matrix B (same as B, but in a different (sorted) order)
> 
> Q, P, T, U, V, .......     (same names, but different order) - has one value
> 
> I need to create a master matrix with data from these two.
> 
> How do I take the numerical value for Q (from Matrix B) and append it to the
> values in Matrix A. (so it becomes the 5th value in the master file)
> 
> Thank you very much
> 
> Srid Iyer
A small reproducible example would have been nice. Anyways, let's build
two matrices:
A <- matrix(runif(4*10), 10)
rownames(A) <- LETTERS[1:10]
B <- matrix(runif(10), 10)
rownames(B) <- sample(LETTERS[1:10])

Then you can just do:
C <- cbind(A, B[match(rownames(A), rownames(B)),])

or, if A is sorted by row names (depends on the locale...) :
D <- cbind(A, B[order(rownames(B)),])

Regards




More information about the R-help mailing list