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

How to Use rbind in R (With Examples)

by Erma Khan

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

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

Example 1: Rbind Vectors into a Matrix

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

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

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

Example 2: Rbind Vector to a Data Frame

The following code shows how to use rbind to row-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 #rbind vector to data frame
df_new #view data frame
df_new

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

Example 3: Rbind Multiple Vectors to a Data Frame

The following code shows how to use rbind to row-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 #rbind vectors to data frame
df_new #view data frame
df_new

   a  b  c
1  1  7  3
2  3  7  3
3  3  8  6
4  4  3  6
5  5  2  8
6 11 14 16
7 34 35 36

Example 4: Rbind Two Data Frames

The following code shows how to use rbind to row-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(a=c(11, 14, 16, 17, 22),
                  b=c(34, 35, 36, 36, 40),
                  c=c(2, 2, 5, 7, 8))

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

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

Note that R will throw an error in either of the following scenarios:

  • The data frames don’t have the same number of columns.
  • The data frames don’t have the same column names.

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

Related Posts