How can multiple data frames be merged in R language?
In R language, you can merge multiple data frames using either the merge() function or the rbind() function.
- Merge data frames using the merge() function:
# 创建两个数据框 df1 和 df2
df1 <- data.frame(ID = c(1, 2, 3),
Name = c("Tom", "Jerry", "Mickey"))
df2 <- data.frame(ID = c(2, 3, 4),
Age = c(20, 25, 30))
# 使用merge()函数合并数据框
merged_df <- merge(df1, df2, by = "ID", all = TRUE)
print(merged_df)
In the above code, the merge() function has the first argument as the two data frames to be merged, the by parameter specifies which variable to merge on, and setting the all parameter to TRUE keeps all merge results.
- Combine data frames using the rbind() function.
# 创建两个数据框 df1 和 df2
df1 <- data.frame(ID = c(1, 2, 3),
Name = c("Tom", "Jerry", "Mickey"))
df2 <- data.frame(ID = c(2, 3, 4),
Name = c("John", "Alice", "Bob"))
# 使用rbind()函数合并数据框
merged_df <- rbind(df1, df2)
print(merged_df)
In the above code, the rbind() function takes as parameters two or more data frames to be merged, combining them row by row into a new data frame.
It is important to note that when merging data frames, ensure that the variables to be merged are of the same type and in the same order to avoid getting incorrect results.