We use the rbind()
and the cbind()
functions to combine two data frames together in R.
rbind()
- combines two data frames verticallycbind()
- combines two data frames horizontally
Example 1: Combine Dataframe Vertically Using rbind() in R
If we want to combine two data frames vertically, the column name of the two data frames must be the same. For example,
# create a data frame
dataframe1 <- data.frame (
Name = c("Juan", "Alcaraz"),
Age = c(22, 15)
)
# create another data frame
dataframe2 <- data.frame (
Name = c("Yiruma", "Bach", "Ludovico"),
Age = c(46, 89, 72)
)
# combine two data frames vertically
updated <- rbind(dataframe1, dataframe2)
print(updated)
Output
Name Age 1 Juan 22 2 Alcaraz 15 3 Yiruma 46 4 Bach 89 5 Ludovico 72
In the above example,we have created a dataframe named dataframe1, with two elements for both the columns and dataframe2, with three elements for both the columns.
And we have combined them together vertically using rbind()
.
Since we want to combine two data frames vertically, we have provided the same column name Name
and Age
for both the data frames.
Example 2: Combine Dataframe Horizontally Using cbind() in R
The cbind()
function combines two or more data frames horizontally. For example,
# create a data frame
dataframe1 <- data.frame (
Name = c("Juan", "Alcaraz"),
Age = c(22, 15)
)
# create another data frame
dataframe2 <- data.frame (
Hobby = c("Tennis", "Piano")
)
# combine two data frames horizontally
updated <- cbind(dataframe1, dataframe2)
print(updated)
Output
Name Age Hobby 1 Juan 22 Tennis 2 Alcaraz 15 Piano
Here, we have used cbind()
to combine two data frames: dataframe1 and dataframe2 horizontally.
And finally the combined dataframe which is stored in the updated variable is printed.
Note: The number of items on each vector of two or more combining data frames must be equal otherwise we will get an error: arguments imply differing number of rows or columns
.