问题
What I am asking is probably quite simple but I still didn't figure out a quick and simple way to do it.
I have data frame with 96 columns from A1 to H12. I will start receiving files every week that I want to compile in one single data frame. The problem is that this files miss some of the columns (that can be the first columns or any other column in the middle) thus making the merge slightly nasty.
Here is a sample of what I have:
t = data.frame(A1 = c(1,2,3,4,5), B1 = c(7,8,9,10,11), C1 = c(10,2,3,7,8), D1 = c(3,6,7,1,2))
> t
A1 B1 C1 D1
1 1 7 10 3
2 2 8 2 6
3 3 9 3 7
4 4 10 7 1
5 5 11 8 2
What I want to do is when I receive a new dataframe to add it based on the column names and fill the rest with NA like this:
new df:
t2 = data.frame(B1 = c(2,4), C1 = c(5,7))
> t2
B1 C1
1 2 5
2 4 7
merge:
A1 B1 C1 D1
1 1 7 10 3
2 2 8 2 6
3 3 9 3 7
4 4 10 7 1
5 5 11 8 2
6 NA 2 5 NA
7 NA 4 7 NA
Is there an easy way to do this?
Thank you all in advance, Cheers
回答1:
You can use dplyr
's bind_rows
:
library(dplyr)
bind_rows(t, t2)
来源:https://stackoverflow.com/questions/37585517/adding-rows-to-a-dataframe-based-on-column-names-and-add-na-to-empty-columns