Attach two matrices in R without losing dimnames

How can I add two matrices without losing 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")))

What 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 add 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 lost the names "Processing" and "Lock" in the sizes of the rows and columns.

Is there an easy way to add these two without losing dimnames?

In this case, it is good to either assume that the dimnames are the same, or to assume that we just want all dimnames to have the first object.

+4
source share
2 answers

Here is 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
+4
source

One thing that comes to mind is to use meltfrom "reshape2" and xtabs:

library(reshape2)
xtabs(value ~ Treatment + Loc, rbind(melt(m1), melt(m2)))
#          Loc
# Treatment North South
#      no1   35.3  25.9
#      yes1  31.7  15.8
#      no2    9.5   7.4
#      yes2   9.6   4.0

, rbind, dimnames, . :

myFun <- function(...) {
  Lst <- list(...)
  Bound <- do.call(rbind, Lst)
  names(dimnames(Bound)) <- names(dimnames(Lst[[1]]))
  Bound
}

names dimnames names dimnames .

xtabs : dimnames (, rownames), xtabs sum . , , :

xtabs(value ~ Treatment + Loc, rbind(melt(m1), melt(m2), melt(m2)))
myFun(m1, m2, m2)
+3

All Articles