Reputation: 1359
Let's say I have the following data-frames:
a<-data.frame(A=3,B=9,C=10,D=6)
print(a)
A B C D
1 3 9 10 6
b<-data.frame(A=1,B=2,D=5)
print(b)
A B D
1 1 2 5
I am trying to bind these together by row so that the corresponding column names line up, and NAs are yielded where corresponding values are missing so that the final result is:
print(c)
A B C D
1 3 9 6 10
2 1 2 NA 5
I have tried the following:
rbind(a,b)
merge(a,b,byrow=TRUE)
But neither work, any suggestions? Thank you!
Upvotes: 1
Views: 544
Reputation: 887138
We can use rbindlist
from data.table
. We keep the data.frames in a list
and use rbindlist
with the option fill=TRUE
to generate NA for missing columns in a dataset.
library(data.table)
rbindlist(list(a,b), fill=TRUE)
# A B C D
#1: 3 9 10 6
#2: 1 2 NA 5
Another option is bind_rows
from dplyr
which is an efficient implementation of do.call(rbind, ...)
for row binding many dataframes together.
library(dplyr)
bind_rows(a,b)
#Source: local data frame [2 x 4]
# A B C D
# (dbl) (dbl) (dbl) (dbl)
#1 3 9 10 6
#2 1 2 NA 5
Upvotes: 3
Reputation: 1189
You could use joins, as implemented in dplyr
.
full_join(a,b)
Joining by: c("A", "B", "D")
A B C D
1 3 9 10 6
2 1 2 NA 5
Upvotes: 2