How to Combine DataFrames Vertically in R

Here are two ways to combine DataFrames vertically in R (stacking them on top of each other):

(1) Using the rbind function:

combined_df <- rbind(df1, df2)

(2) Using the bind_rows function from the dplyr package:

library(dplyr)

combined_df <- bind_rows(df1, df2)

Note that you’ll need to make sure the columns in all the DataFrames have the same names and are in the same order.

Examples of Combining DataFrames Vertically in R

Example 1: Using the rbind function

To combine the DataFrames vertically using the rbind function:

df1 <- data.frame(product = c("computer", "monitor", "keyboard"),
                  price = c(800, 450, 100)
                 )

df2 <- data.frame(product = c("printer", "tablet"),
                  price = c(150, 300)
                 )

combined_df <- rbind(df1, df2)

print(combined_df)

The result:

   product  price
1 computer    800
2  monitor    450
3 keyboard    100
4  printer    150
5   tablet    300

Example 2: Using the bind_rows function from the dplyr package

If you haven’t already done so, install the dplyr package using:

install.packages("dplyr")

Then, combine the DataFrames as follows:

library(dplyr)

df1 <- data.frame(product = c("computer", "monitor", "keyboard"),
                  price = c(800, 450, 100)
                 )

df2 <- data.frame(product = c("printer", "tablet"),
                  price = c(150, 300)
                 )

combined_df <- bind_rows(df1, df2)

print(combined_df)

The result:

   product  price
1 computer    800
2  monitor    450
3 keyboard    100
4  printer    150
5   tablet    300

Leave a Comment