Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append two matrices in R without losing dimnames

Tags:

append

r

matrix

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.

like image 333
Glen_b Avatar asked Mar 19 '23 14:03

Glen_b


1 Answers

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
like image 81
thelatemail Avatar answered Apr 25 '23 15:04

thelatemail