How to combine data frames vertically in R

Overview

In this shot, we will look at combining two or more data frames in R.

Combining data frames

The rbind() function combines data frames vertically in R.

Syntax

rbind(dataframe1, dataframe2)

Parameter value

The rbind() function can take two or more parameter values representing the respective data frames to be combined vertically.

Return value

The rbind() function returns vertically combined data frames.

Code example

# creating the 1st data frame
My_Data_Frame1 <- data.frame (
Height = c("Tall", "Average", "short"),
Body_structure = c("Meso", "Endo", "Ecto"),
Age = c(35, 30, 45)
)
# creating the 2nd data frame
My_Data_Frame2 <- data.frame (
Height = c("Average", "Tall", "short"),
Body_structure = c("Endo", "Endo", "Ecto"),
Age = c(20, 30, 45)
)
# combining the data frames
New_Data_Frame <- rbind(My_Data_Frame1, My_Data_Frame2)
New_Data_Frame

Code explanation

  • Line 2: We create a data frame object, My_Data_Frame1, with three columns.
  • Line 9: We create a second data frame object, My_Data_Frame2, with three columns as well.
  • Line 16: We combine My_Data_Frame1 and My_Data_Frame2 vertically using the rbind() function. The output is assigned to another variable named New_Data_Frame.
  • Line 17: We print the newly created New_Data_Frame.

Free Resources