The rbind() Function In R: How To Use rbind() In R

rbind function in r

The rbind() function in R combines rows of two data sets like vectors, data frames, and matrices. Please check out our instructions below for more explanation about this function and applications. We will also show you some of the most common ways to use it in our program. 

What does the rbind() function do in R?

The “rbind” stands for row binding. So the idea of the rbind() function is to bind two vectors, data frames, or matrices by rows. Here is a diagram that might give you a better understanding of this function:

Example: 

x1 <- c(32, 24, 34, 21, 45, 98, 77, 90, 43, 11, 55, 24)
x2 <- c(94, 32, 595, 45, 16, 1, 24, 91, 18, 10, 21, 11)

rbind(x1, x2)

Output:

   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
x1   32   24   34   21   45   98   77   90   43    11    55    24
x2   94   32  595   45   16    1   24   91   18    10    21    11

How to use the rbind() function in R?

Syntax:

rbind(x1, x2)

Parameters:

  • x1, x2: can be vectors, data frames, matrices,…

Example of binding 2 vectors to get a matrix:

vt1 <- c(34, 30, 22, 99, 86, 35, 68, 51, 32, 80)
vt2 <- c(27, 4, 27, 30, 39, 20, 82, 51, 3, 45)

matrix = rbind(vt1, vt2)
matrix

Output:

    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
vt1   34   30   22   99   86   35   68   51   32    80
vt2   27    4   27   30   39   20   82   51    3    45

Example of binding vectors to a data frame:

data <- data.frame(
    Col_1 = c(24, 16, 64, 84, 32, 81, 57, 44, 44, 89),
    Col_2 = c(98, 33, 39, 73, 11, 34, 90, 40, 82, 57),
    Col_3 = c(11, 20, 82, 15, 15, 62, 99, 27, 59, 51)
)

x1 <- c(20, 83, 36)
x2 <- c(39, 7, 41)

rbind(data, x1, x2)

Output:

   Col_1 Col_2 Col_3
1     24    98    11
2     16    33    20
3     64    39    82
4     84    73    15
5     32    11    15
6     81    34    62
7     57    90    99
8     44    40    27
9     44    82    59
10    89    57    51
11    20    83    36
12    39     7    41

However, there are some exceptions. If our data frames have different numbers of columns or different column names, our program will run into an error. 

In addition to the rbind() function is the cbind() function. It will bind two vectors, data frames, or matrices by column, instead of row.

Summary

In this tutorial, we have demonstrated the rbind() function in R and how to apply it into our program. The idea of the rbind() function is to vectors, data frames, or matrices by row.

Maybe you are interested:

Posted in R

Leave a Reply

Your email address will not be published. Required fields are marked *