Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating Matrices in R

How can I concatenate matrices of same columns but different number of rows? For example, I want to concatenate a (dim(a) = 15 7000) and b (dim(b) = 16 7000) and I want the result to be a matrix of 31 rows by 7000 columns.

Can I also do this for matrices with a different number of rows and columns? Say I want to combine a matrix of 15 rows and 7000 columns with another of 16 rows and 7500 columns. Can I create one dataset with that?

like image 556
Concerned_Citizen Avatar asked Sep 06 '11 19:09

Concerned_Citizen


People also ask

How do you concatenate matrices in R?

Combining two matrices in R To combine two or more matrices in R, we use the following functions: rbind() : Used to add the matrices as rows. cbind() : Used to add the matrices as columns.

How do you combine two matrices?

Concatenating Matrices You can also use square brackets to join existing matrices together. This way of creating a matrix is called concatenation. For example, concatenate two row vectors to make an even longer row vector. To arrange A and B as two rows of a matrix, use the semicolon.

What does as matrix do in R?

as. matrix converts its first argument into a matrix, the dimensions of which will be inferred from the input. matrix creates a matrix from the given set of values. as.

How do you combine two matrices in Python?

Use numpy. concatenate : >>> import numpy as np >>> np. concatenate((A, B)) matrix([[ 1., 2.], [ 3., 4.], [ 5., 6.]])


1 Answers

Sounds like you're looking for rbind:

> a<-matrix(nrow=10,ncol=5) > b<-matrix(nrow=20,ncol=5) > dim(rbind(a,b)) [1] 30  5 

Similarly, cbind stacks the matrices horizontally.

I am not entirely sure what you mean by the last question ("Can I do this for matrices of different rows and columns.?")

like image 95
NPE Avatar answered Oct 04 '22 04:10

NPE