Wednesday, June 20, 2018

What are rbind and cbind for matrices in R?

rbind is short for row bind. rbind binds concatenated datapoints into matrix of compatible dimensions. cbind does the same taking column data.

Let us take the matrix defined in an earlier post:


MTX_0

In the above the matrix is:
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9

This has three rows. Let us define the following:

row1=c(1,2,3)
row2=c(4,5,6)
row3=c(7,8,9)


We can define the same matrix using rbind as shown below.

mtx2=rbind(row1,row2,row3)
Then we can form the matrix using the rbind as shown here:


MTX_1
 
There is a slight difference in the displayed results. However, you can perform this to get the matrix displayed in the original format as shown here:


MTX_2

The cbind works the same way as rbind. Instead of binding row-wise you bind column-wise. Of course you need to use the columns correctly.


MTX_3

No comments: