I need to merge 2 data frames while preserving their order of appearance in each data frame :
x = data.frame(a=1:3, b=2:4, c=3:5)
y = data.frame(a=c(10, 20, 30), b=c(20, 30, 40), c=c(30, 40, 50))
What I want is :
> z
a b c
1 2 3
10 20 30
2 3 4
20 30 40
3 4 5
30 40 50
But what rbind does is it's adding the second dataframe under the first.
Try this one-liner
which gives this data.frame if
x
andy
are as in the question:It splits each data frame by row and then will rbind corresponding components of the splits. Then it rbinds all that. Note that this one-liner works even if the columns have different types. For example it will work even if:
As yet another base r version:
Created on 2019-02-14 by the reprex package (v0.2.1)
You could use the row number idea from Paweł in base
R
:edit can also use rownames generated by rbind():
You should add row number variable to each data frame and sort by this variable after binding. With
dplyr
you can do this as follow:Just for the sake of completeness, also a
data.table
solution.