You can use the bind_rows() and bind_cols() functions to combine data from multiple sources or augment existing datasets more efficiently.
bind_rows()
The bind_rows() function from the dplyr package is used to combine two or more data frames by their rows.
This function assumes that the columns in the different data frames have the same names and types. If a column is present in one data frame but not in another, it will be filled with NA in the rows corresponding to the data frame where it’s missing.
Syntax
bind_rows(df1, df2, df3, ...)
Parameters
df1, df2: It is the data frames to combine.
Visual representation
Example
library(dplyr)
# Creating two data frames.
df1 <- data.frame(x = 1:3, y = 4:6)
df2 <- data.frame(x = 7:9, y = 10:12)
# Binding the data frames by row
df <- bind_rows(df1, df2)
# Printing the data frame.
print(df)
Output
bind_cols()
The bind_cols() function from the dplyr package is used to combine two or more data frames by columns.
This function requires that the number of rows in the data frames is the same. It adds columns side by side.
Syntax
bind_cols(df1, df2, df3)
Parameters
df1, df2: It is the data frames to combine.
Visual representation
Example
library(dplyr)
# Creating two data frames.
df1 <- data.frame(x = 1:3, y = 4:6)
df2 <- data.frame(z = 7:9, w = 10:12)
# Combine the columns of the two data frames using bind_cols()
df <- bind_cols(df1, df2)
cat("After binding two data frames by cols", "\n")
# Printing the data frame.
df
Output
Related posts
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.