Combining Data Frames in R
There are 2 way to combine data frames in R. You can either combine them vertically or horizontally.
Let’s look at both cases with example:
Combine R Data Frame Vertically
If you want to combine 2 data frames vertically, you can use rbind() function. This function works for combination of two or more data frames.
R
# Creating two sample dataframes df1 <- data.frame ( Name = c ( "Alice" , "Bob" ), Age = c (25, 30), Score = c (80, 75) ) df2 <- data.frame ( Name = c ( "Charlie" , "David" ), Age = c (28, 35), Score = c (90, 85) ) # Print the existing dataframes cat ( "Dataframe 1:\n" ) print (df1) cat ( "\nDataframe 2:\n" ) print (df2) # Combining the dataframes using rbind() combined_df <- rbind (df1, df2) # Print the combined dataframe cat ( "\nCombined Dataframe:\n" ) print (combined_df) |
Output:
Dataframe 1:
Name Age Score
1 Alice 25 80
2 Bob 30 75
Dataframe 2:
Name Age Score
1 Charlie 28 90
2 David 35 85
Combined Dataframe:
Name Age Score
1 Alice 25 80
2 Bob 30 75
3 Charlie 28 90
4 David 35 85
Combine R Data Frame Horizontally:
If you want to combine 2 data frames horizontally, you can use cbind() function. This function works for combination of two or more data frames.
R
# Creating two sample dataframes df1 <- data.frame ( Name = c ( "Alice" , "Bob" ), Age = c (25, 30), Score = c (80, 75) ) df2 <- data.frame ( Height = c (160, 175), Weight = c (55, 70) ) # Print the existing dataframes cat ( "Dataframe 1:\n" ) print (df1) cat ( "\nDataframe 2:\n" ) print (df2) # Combining the dataframes using cbind() combined_df <- cbind (df1, df2) # Print the combined dataframe cat ( "\nCombined Dataframe:\n" ) print (combined_df) |
Output:
Dataframe 1:
Name Age Score
1 Alice 25 80
2 Bob 30 75
Dataframe 2:
Height Weight
1 160 55
2 175 70
Combined Dataframe:
Name Age Score Height Weight
1 Alice 25 80 160 55
2 Bob 30 75 175 70
Also Read:
In this article we have covered R Data Frames, and all basic operations like create, access, summary, add and remove. This article purposes to make you familiar with data frames in R so that you can use it in your projects.
Hope this helps you in understanding the concept of data frames in R and you can easily implement R data frame in your projects.
R – Data Frames
R Programming Language is an open-source programming language that is widely used as a statistical software and data analysis tool. Data Frames in R Language are generic data objects of R that are used to store tabular data.
Data frames can also be interpreted as matrices where each column of a matrix can be of different data types. R DataFrame is made up of three principal components, the data, rows, and columns.