Home » How to Use cbind in R (With Examples)

How to Use cbind in R (With Examples)

by Erma Khan

The cbind function in R, short for column-bind, can be used to combine vectors, matrices and data frames by column.

The following examples show how to use this function in practice.

Example 1: Cbind Vectors into a Matrix

The following code shows how to use cbind to column-bind two vectors into a single matrix:

#create two vectors
a #cbind the two vectors into a matrix
new_matrix #view matrix
new_matrix

     a b
[1,] 1 7
[2,] 3 7
[3,] 3 8
[4,] 4 3
[5,] 5 2

#view class of new_matrix
class(new_matrix)

[1] "matrix" "array" 

Example 2: Cbind Vector to a Data Frame

The following code shows how to use cbind to column-bind a vector to an existing data frame:

#create data frame
df frame(a=c(1, 3, 3, 4, 5),
                 b=c(7, 7, 8, 3, 2),
                 c=c(3, 3, 6, 6, 8))

#define vector
d #cbind vector to data frame
df_new #view data frame
df_new

  a b c  d
1 1 7 3 11
2 3 7 3 14
3 3 8 6 16
4 4 3 6 17
5 5 2 8 22

Note that R will throw an error if the length of the vector is not the same as the length of the columns in the existing data frame.

Example 3: Cbind Multiple Vectors to a Data Frame

The following code shows how to use cbind to column-bind multiple vectors to an existing data frame:

#create data frame
df frame(a=c(1, 3, 3, 4, 5),
                 b=c(7, 7, 8, 3, 2),
                 c=c(3, 3, 6, 6, 8))

#define vectors
d #cbind vectors to data frame
df_new #view data frame
df_new

  a b c  d  e
1 1 7 3 11 34
2 3 7 3 14 35
3 3 8 6 16 36
4 4 3 6 17 36
5 5 2 8 22 40

Example 4: Cbind Two Data Frames

The following code shows how to use cbind to column-bind two data frames into one data frame:

#create two data frames
df1 frame(a=c(1, 3, 3, 4, 5),
                  b=c(7, 7, 8, 3, 2),
                  c=c(3, 3, 6, 6, 8))

df2 frame(d=c(11, 14, 16, 17, 22),
                  e=c(34, 35, 36, 36, 40))

#cbind two data frames into one data frame
df_new #view data frame
df_new

  a b c  d  e
1 1 7 3 11 34
2 3 7 3 14 35
3 3 8 6 16 36
4 4 3 6 17 36
5 5 2 8 22 40

Bonus: If you want to bind together vectors, matrices, or data frames by rows, you can used the rbind function instead.

Related Posts