How to merge two unequal data frames and replace missing values to 0 in R?


Often, we get data frames that are not of same size that means some of the rows or columns are missing in any of the data frames. Therefore, to merge these types of data frames we can merge them with all of their values and convert the missing values to zero if necessary. This can be done by using merge function and replacement of missing values NA to zeros should be done by using single square brackets.

Example

Consider the below data frames −

> C1<-LETTERS[1:10]
> df1<-data.frame(C1)
> df1
C1
1 A
2 B
3 C
4 D
5 E
6 F
7 G
8 H
9 I
10 J
> x1<-c(1,2,3,4,5)
> C1<-LETTERS[1:5]
> df2<-data.frame(x1,C1)
> df2
x1 C1
1 1 A
2 2 B
3 3 C
4 4 D
5 5 E

Merging the data frames df1 and df2 −

> df<-merge(df1,df2,all=TRUE)
> df
C1 x1
1 A 1
2 B 2
3 C 3
4 D 4
5 E 5
6 F NA
7 G NA
8 H NA
9 I NA
10 J NA

Since we have NA’s in df, we can replace it with 0 as follows −

> df[is.na(df)]<-0
> df
C1 x1
1 A 1
2 B 2
3 C 3
4 D 4
5 E 5
6 F 0
7 G 0
8 H 0
9 I 0
10 J 0

Updated on: 12-Aug-2020

811 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements