How can I append two matrices without losing the dimnames?
Set up some data:
m1 <- structure(c(35.3, 31.7, 25.9, 15.8),
.Dim = c(2L, 2L),
.Dimnames = structure(list(
Treatment = c("no1", "yes1"), Loc = c("North", "South")),
.Names = c("Treatment", "Loc")))
m2 <- structure(c(9.5, 9.6, 7.4, 4.0),
.Dim = c(2L, 2L),
.Dimnames = structure(list(
Treatment = c("no2", "yes2"), Loc = c("North", "South")),
.Names = c("Treatment", "Loc")))
Which gives:
> m1
Loc
Treatment North South
no1 35.3 25.9
yes1 31.7 15.8
> m2
Loc
Treatment North South
no2 9.5 7.4
yes2 9.6 4.0
But if I append them with rbind
:
> rbind(m1,m2)
North South
no1 35.3 25.9
yes1 31.7 15.8
no2 9.5 7.4
yes2 9.6 4.0
I've lost the "Treatment" and "Loc" names on the row and column dimensions.
Is there a straightforward way to append the two without losing the dimnames?
It's okay in this case to either assume the dimnames are the same, or to assume we simply want whatever dimnames the first object has.
Here's one way:
out <- rbind(m1,m2)
names(dimnames(out)) <- names(dimnames(m1))
# Loc
#Treatment North South
# no1 35.3 25.9
# yes1 31.7 15.8
# no2 9.5 7.4
# yes2 9.6 4.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With