What is the rbind() function in R?
Overview
The rbind() function represents a row bind function for vectors, data frames, and matrices to be arranged as rows. It is used to combine multiple data frames for data manipulation.
There are three ways to bind rows using rbind(), shown in code snippets below.
Syntax
# Signaturerbind(input_data, data_to_bind)
Parameters
It takes the following argument values.
input_data: This is the input data.data_to_bind: This is the data that will be bounded.
Return value
It returns a combined vector, DataFrame, matrix, or other DataType values. The return values also depend upon input_data.
Explanation
Let's discuss some coding examples related to rbind(). It's used to bind rows and columns to combine different vectors, data frames, or matrices.
# Assigning two vectorsx <- 1:12y <- c(2, 11, 3)# Calling rbind() functionrbind(x, y)
- Lines 2–3: We create two random vectors of different lengths.
- Line 5: We call the
rbind()function to bind thexandyvectors.
It can also be used to combine and convert DataFrames, vectors, and matrices. Given below are a few examples of it.
Bind a DataFrame and vector
rbind() can be used to convert vectors to a DataFrame. Here's an example.
# creating vectors using c() functionx1 <- c(7, 6, 4, 9)x2 <- c(5, 2, 7, 9)x3 <- c(11, 2, 5, 4)# creating a DataFrame with above# generated vectorsdata <- data.frame(x1, x2, x3)# a new vector to bindmyVector <- c(9, 6, 7)# implementing the rbind functionrbind(data, myVector)
- Lines 2–4: We create
x1,x2, andx3data frames on random values. - Line 7: We combine to create a DataFrame
data. - Line 9: We create a vector with 9, 6 and 7.
- Line 11: We implement the
rbind()that takes a data framedataas its first argument andmyVectoras its second argument to combine.
Bind two DataFrames
rbind() function combines similar data types as well. In the code snippet below, we are going to bind two data frames data1 and data2.
# create vectors using c() functiona1 <- c(7, 1)a2 <- c(4, 1)a3 <- c(4, 3)# create a DataFrame data1data1 <- data.frame(a1, a2, a3)# Create another DataFrame data2data2 <- data.frame(a1, a2, a3)# combining data1 and data2 DataFramesrbind(data1, data2)
- Lines 2–4: We create three vectors to convert them into a DataFrame.
- Lines 6–8: We create two data frames
data1anddata2to hold the data. - Line 10: We implement the
rbind()function to bind the created DataFrames.