How to combine two data frames by filling NA in empty places in R?

R ProgrammingServer Side ProgrammingProgramming

To combine two data frames by filling NA in empty places, we can use rbind_fill function of plyr package.

For example, if we have two data frames say DF1 and DF2 that have some common and some uncommon columns then we can combine them by using the below given command −

rbind.fill(DF1,DF2)

Example

Following snippet creates a sample data frame −

df1<-mtcars[1:20,c("mpg","hp","gear")]
df1

Output

The following dataframe (df1) is created −

                    mpg   hp  gear
Mazda RX4           21.0  110  4
Mazda RX4 Wag       21.0  110  4
Datsun 710          22.8   93  4
Hornet 4 Drive      21.4  110  3
Hornet Sportabout   18.7  175  3
Valiant             18.1  105  3
Duster 360          14.3  245  3
Merc 240D           24.4   62  4
Merc 230            22.8   95  4
Merc 280            19.2  123  4
Merc 280C           17.8  123  4
Merc 450SE          16.4  180  3
Merc 450SL          17.3  180  3
Merc 450SLC         15.2  180  3
Cadillac Fleetwood  10.4  205  3
Lincoln Continental 10.4  215  3
Chrysler Imperial   14.7  230  3
Fiat 128            32.4   66  4
Honda Civic         30.4   52  4
Toyota Corolla      33.9   65  4

Following snippet creates a sample data frame −

df2<-mtcars[21:32,c("mpg","disp","gear")]
df2

The following dataframe (df2) is created −

                 mpg   disp  gear
Toyota Corona    21.5  120.1  3
Dodge Challenger 15.5  318.0  3
AMC Javelin      15.2  304.0  3
Camaro Z28       13.3  350.0  3
Pontiac Firebird 19.2  400.0  3
Fiat X1-9        27.3  79.0   4
Porsche 914-2    26.0  120.3  5
Lotus Europa     30.4  95.1   5
Ford Pantera L   15.8  351.0  5
Ferrari Dino     19.7  145.0  5
Maserati Bora    15.0  301.0  5
Volvo 142E       21.4  121.0  4

Now, in order to load plyr package and combine data frames df1 and df2, add the following code to the above snippet −

library(plyr)
df<-rbind.fill(df1,df2)
df

Output

If you execute all the above given snippets as a single program, it generates the following output −

   mpg   hp  gear disp
1  21.0  110  4   NA
2  21.0  110  4   NA
3  22.8   93  4   NA
4  21.4  110  3   NA
5  18.7  175  3   NA
6  18.1  105  3   NA
7  14.3  245  3   NA
8  24.4   62  4   NA
9  22.8   95  4   NA
10 19.2  123  4   NA
11 17.8  123  4   NA
12 16.4  180  3   NA
13 17.3  180  3   NA
14 15.2  180  3   NA
15 10.4  205  3   NA
16 10.4  215  3   NA
17 14.7  230  3   NA
18 32.4   66  4   NA
19 30.4   52  4   NA
20 33.9   65  4   NA
21 21.5   NA  3  120.1
22 15.5   NA  3  318.0
23 15.2   NA  3  304.0
24 13.3   NA  3  350.0
25 19.2   NA  3  400.0
26 27.3   NA  4  79.0
27 26.0   NA  5  120.3
28 30.4   NA  5  95.1
29 15.8   NA  5  351.0
30 19.7   NA  5  145.0
31 15.0   NA  5  301.0
32 21.4   NA  4  121.0
raja
Updated on 06-Nov-2021 06:20:59

Advertisements