[R] Merging Matrices
Steven McKinney
smckinney at bccrc.ca
Sat Mar 20 03:50:37 CET 2010
________________________________________
> From: r-help-bounces at r-project.org [r-help-bounces at r-project.org] On Behalf Of duncandonutz [dwadswor at unm.edu]
> Sent: March 19, 2010 1:11 PM
> To: r-help at r-project.org
> Subject: [R] Merging Matrices
>
> 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.
With appropriate indexing of the matrices via their shared names,
it can be done as follows:
> A <- matrix(1:9, nrow = 3)
> A[lower.tri(A)] <- A[upper.tri(A)]
> B <- matrix(1:25, nrow = 5)
> B[lower.tri(B)] <- B[upper.tri(B)]
> dimnames(A) <- list(letters[c(2, 4, 5)], letters[c(2, 4, 5)])
> dimnames(B) <- list(letters[1:5], letters[1:5])
> A
b d e
b 1 4 7
d 4 5 8
e 7 8 9
> B
a b c d e
a 1 6 11 16 21
b 6 7 12 17 22
c 11 17 13 18 23
d 12 18 22 19 24
e 16 21 23 24 25
> B[dimnames(A)[[1]], dimnames(A)[[1]]]
b d e
b 7 17 22
d 18 19 24
e 21 24 25
> C <- B
> C[dimnames(A)[[1]], dimnames(A)[[1]]] <- A + B[dimnames(A)[[1]], dimnames(A)[[1]]]
> C
a b c d e
a 1 6 11 16 21
b 6 8 12 21 29
c 11 17 13 18 23
d 12 22 22 24 32
e 16 28 23 32 34
> C - B
a b c d e
a 0 0 0 0 0
b 0 1 0 4 7
c 0 0 0 0 0
d 0 4 0 5 8
e 0 7 0 8 9
>
HTH
Steve McKinney
> 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