Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

r
function
communitycreator

How to combine data frames horizontally in R

Onyejiaku Theophilus Chidalu

Overview

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

Combining data frames

The cbind() function combines data frames horizontally in R.

Syntax

cbind(dataframe1, dataframe2)

Parameter value

The cbind() function takes two or more parameter values that represent the respective data frames to be combined horizontally.

Return value

The cbind() function returns horizontally 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 <- cbind(My_Data_Frame1, My_Data_Frame2)
New_Data_Frame
Implementing the cbind() function

Code explanation

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

RELATED TAGS

r
function
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring