How to Use bind_rows() and bind_cols() Functions in R

You can use the bind_rows() and bind_cols() functions to combine data from multiple sources or augment existing datasets more efficiently.

bind_rows()

The bind_rows() function from the dplyr package is used to combine two or more data frames by their rows.

This function assumes that the columns in the different data frames have the same names and types. If a column is present in one data frame but not in another, it will be filled with NA in the rows corresponding to the data frame where it’s missing.

Syntax

bind_rows(df1, df2, df3, ...)

Parameters

df1, df2: It is the data frames to combine.

Visual representation

Visual representation of bind_rows() function

Example

library(dplyr)

# Creating two data frames.
df1 <- data.frame(x = 1:3, y = 4:6)
df2 <- data.frame(x = 7:9, y = 10:12)

# Binding the data frames by row
df <- bind_rows(df1, df2)

# Printing the data frame.
print(df)

Output

Output of bind_rows() function

bind_cols()

The bind_cols() function from the dplyr package is used to combine two or more data frames by columns.

This function requires that the number of rows in the data frames is the same. It adds columns side by side.

Syntax

bind_cols(df1, df2, df3)

Parameters

df1, df2: It is the data frames to combine.

Visual representation

Visual representation of bind_cols() function

Example

library(dplyr)

# Creating two data frames.
df1 <- data.frame(x = 1:3, y = 4:6)
df2 <- data.frame(z = 7:9, w = 10:12)

# Combine the columns of the two data frames using bind_cols()
df <- bind_cols(df1, df2)

cat("After binding two data frames by cols", "\n")

# Printing the data frame.
df

Output

Output of bind_cols()

Related posts

rbind() function

cbind() function

Leave a Comment