user3478697
user3478697

Reputation: 253

merge two matrices by column names

i have

mat1 <- matrix(c(1,2,3,4,5,6), ncol=2)
colnames(mat1) <- c("Soa","Nor")
mat2 <- matrix(c(1,0,1,1,0), nrow=1)
colnames(mat2) <- c("reman","jak","Soa","Alein","Nor")

I need to get this matrices

Soa    Nor
1       4
2       5
3       6
1       0

I use this but does not work for column

merge(mat1,mat2, by="row.names", all = TRUE)

Upvotes: 1

Views: 9277

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99331

This is much more simple with rbind. You can extract the relevant columns of mat2 with colnames(mat1) and then bind them together.

> rbind(mat1, mat2[, colnames(mat1)])
#     Soa Nor
#[1,]   1   4
#[2,]   2   5
#[3,]   3   6
#[4,]   1   0

Upvotes: 5

SimonG
SimonG

Reputation: 4871

If you want to stick with merge, you could try this:

samecols <- intersect(colnames(mat1),colnames(mat2))
merge(mat1,mat2, by=samecols, all=TRUE)[samecols]

The difference to your code is, that by is a vector of column names here that both matrices share. As @akrun pointed out in his comment, the same thing can be achieved using rbind by referencing to the columns in the same way.

Upvotes: 1

Related Questions