How to use cbind() function in R

In this tutorial, we will learn how to use cbind() function in R. The cbind() function in the R programming language is used to combine vectors, matrices, or data frames by columns. cbind() stands for column bind as it combines by column.

The basic syntax for using cbind() is as follows:

cbind(x, y, ...)

Here, x and y are the objects that you want to combine. For example, x and y can be vectors, or dataframes.

cbind() example to combine two vectors by column

Let’s take a look at some examples to understand how cbind() works.

# two vectors to combine
x <- c(1, 2, 3)
y <- c(4, 5, 6)

To combine these vectors by columns, we can use cbind():

# example combining two vectors by column
cbind(x, y)

This will output the following matrix:

     x y
[1,] 1 4
[2,] 2 5
[3,] 3 6

As you can see, cbind() has combined two vectors by column and has created a matrix with two columns.

cbind() example to combine a matrix with a vector by column

Let us create a matrix and a vector to combine by column.

# create a matrix
A <- matrix(1:6, nrow = 2, ncol = 3)
A

     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
# create a vector
b <- c(7, 8)

Let us combine the matrix with the vector by column using cbind() function.

# combine a matrix with a vector
cbind(A, z)

And we will get matrix of dimension 4 x 2.

     [,1] [,2] [,3] [,4]
[1,]    1    3    5    7
[2,]    2    4    6    8

As you can see, the vector b has been added as an additional column to the matrix A

cbind() example to combine two matrices by column

Let us construct two matrices with the same number of rows using matrix() function in R.

# construct two matrices
A <- matrix(1:6, nrow = 2, ncol = 3)
B <- matrix(7:12, nrow = 2, ncol = 3)

And the two matrices look like these.

A

##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    4    6
B

##      [,1] [,2] [,3]
## [1,]    7    9   11
## [2,]    8   10   12

Let us combine the two matrices by column. We can see that the B matrix has beed added to the A matrix.

cbind(A,B)

##      [,1] [,2] [,3] [,4] [,5] [,6]
## [1,]    1    3    5    7    9   11
## [2,]    2    4    6    8   10   12

cbind() example to combine two dataframes by column

Let us consider the third example of using cbind(). This time we will use cbind() function to combine two dataframes, df1 and df2.

df1 <- data.frame(a = c(1, 2, 3), 
                  b = c(4, 5, 6))
df2 <- data.frame(c = c(7, 8, 9),
                  d = c(10, 11, 12))

To combine these data frames by columns, we can use cbind():

cbind(df1, df2)

This will output the following data frame:

  a b  c  d
1 1 4  7 10
2 2 5  8 11
3 3 6  9 12

Exit mobile version