Combine Data Frames with Same Columns
To combine two data frames with same columns in R language, call rbind() function, and pass the two data frames, as arguments.
rbind(data_frame_1, data_frame_2)
rbind() function returns the resulting data frame created from concatenating the given two data frames.
For rbind() function to combine the given data frames, the column names must match.
Examples
In the following example, we take two data frames: df1
and df2
, and combine these two data frames using rbind() function.
example.r
df1 <- data.frame(name = c('A', 'B', 'C', 'D'),
age = c(4, 8, 10, 14),
income = c(1.6, 1.5, 1.7, 1.9))
df2 <- data.frame(name = c('E', 'F', 'G'),
age = c(18, 10, 12),
income = c(1.5, 1.0, 1.7))
df_output <- rbind(df1, df2)
print(df_output)
Output
tutorialkart$ Rscript example.r
name age income
1 A 4 1.6
2 B 8 1.5
3 C 10 1.7
4 D 14 1.9
5 E 18 1.5
6 F 10 1.0
7 G 12 1.7
If the column names do not match, then rbind() throws error.
In the following example we take two data frames with different column names, and try to combine using rbind() function.
example.r
df1 <- data.frame(name = c('A', 'B', 'C', 'D'),
points = c(4, 8, 10, 14),
increments = c(1.6, 1.5, 1.7, 1.9))
df2 <- data.frame(name = c('E', 'F', 'G'),
age = c(18, 10, 12),
income = c(1.5, 1.0, 1.7))
df_output <- rbind(df1, df2)
print(df_output)
Output
tutorialkart$ Rscript example.r
Error in match.names(clabs, names(xi)) :
names do not match previous names
Calls: rbind -> rbind -> match.names
Execution halted
Conclusion
In this R Tutorial, we learned how to combine two data frames using rbind() function, with the help of an example programs.