[R] Merging Matrices

David Winsemius dwinsemius at comcast.net
Sat Mar 20 03:09:15 CET 2010


On Mar 19, 2010, at 4:11 PM, duncandonutz wrote:

>
> I have two symmetric matrices, but of different dimensions.  The  
> entries are
> identified by specific labels some of which are shared by both  
> matrices.  I
> would like to sum the two matrices, but retain the union of the  
> two.  In
> other words, I want the result to be the same size as the larger of  
> the two
> matrices, but with the entries that they share added together.
>
> cbind() and rbind() don't work since the matrices are different sizes
> (symmetrically).  Merge doesn't want to cooperate, although it might  
> be
> because I can't understand the documentation. I tried the package  
> "reshape"
> but didn't get very far with that either.  I tried simply adding (+)  
> them,
> but that was a stupid first try.

See if this effort to construct an example and implement what it  
sounds like you are asking is effective:

 > A <- matrix(1:25, 5)
 > B <- matrix(1:9, 3)
 > colnames(A) <- c(letters[1:5])
 > colnames(B) <- c(letters[1:3])
 > rownames(B) <- c(letters[1:3])
 > rownames(A) <- c(letters[1:5])
 > rownames(A)[1] <- "A"
 > intersect(rownames(A),rownames(B))
[1] "b" "c"
 > intersect(colnames(A),colnames(B))
[1] "a" "b" "c"
 >  
A[intersect(rownames(A),rownames(B)),intersect(colnames(A),colnames(B))]
   a b  c
b 2 7 12
c 3 8 13
 >  
B[intersect(rownames(A),rownames(B)),intersect(colnames(A),colnames(B))]
   a b c
b 2 5 8
c 3 6 9
 >  
A 
[intersect 
(rownames(A),rownames(B)),intersect(colnames(A),colnames(B))] <-  
A 
[intersect 
(rownames(A),rownames(B)),intersect(colnames(A),colnames(B))] +  
B[intersect(rownames(A),rownames(B)),intersect(colnames(A),colnames(B))]
 > A
   a  b  c  d  e
A 1  6 11 16 21
b 4 12 20 17 22
c 6 14 22 18 23
d 4  9 14 19 24
e 5 10 15 20 25

-- 
David
>
> Any help is appreciated!
> -- 
> View this message in context: http://n4.nabble.com/Merging-Matrices-tp1605474p1605474.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.



More information about the R-help mailing list