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.

rbind() working

There are three ways to bind rows using rbind(), shown in code snippets below.

Syntax


# Signature
rbind(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 vectors
x <- 1:12
y <- c(2, 11, 3)
# Calling rbind() function
rbind(x, y)
  • Lines 2–3: We create two random vectors of different lengths.
  • Line 5: We call the rbind() function to bind the x and y vectors.

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() function
x1 <- c(7, 6, 4, 9)
x2 <- c(5, 2, 7, 9)
x3 <- c(11, 2, 5, 4)
# creating a DataFrame with above
# generated vectors
data <- data.frame(x1, x2, x3)
# a new vector to bind
myVector <- c(9, 6, 7)
# implementing the rbind function
rbind(data, myVector)
  • Lines 2–4: We create x1, x2, and x3 data 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 frame data as its first argument and myVector as 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() function
a1 <- c(7, 1)
a2 <- c(4, 1)
a3 <- c(4, 3)
# create a DataFrame data1
data1 <- data.frame(a1, a2, a3)
# Create another DataFrame data2
data2 <- data.frame(a1, a2, a3)
# combining data1 and data2 DataFrames
rbind(data1, data2)
  • Lines 2–4: We create three vectors to convert them into a DataFrame.
  • Lines 6–8: We create two data frames data1 and data2 to hold the data.
  • Line 10: We implement the rbind() function to bind the created DataFrames.

Free Resources