简体   繁体   中英

Adding rows to a dataframe based on column names and add NA to empty columns

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

You can use dplyr 's bind_rows :

library(dplyr)
bind_rows(t, t2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM