- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- How to merge data frames by row names in R?
- How to multiply corresponding values from two data frames in R?
- How to replace missing values with row means in an R data frame?
- How to replace missing values with median in an R data frame column?
- How to match and replace column names stored in R data frames in R-Programming?
- How to fill missing values after merging the data frames with another value than NA in R?
- How to replace NA with 0 and other values to 1 in an R data frame column?
- How to replace missing values in a column with corresponding values in other column of an R data frame?
- How to convert a column with missing values to binary with 0 for missing values in R?
- How to merge two data frames of different length having same values in all columns but at different positions?
- How to replace missing values with linear interpolation method in an R vector?
- How to use pandas series.fillna() to replace missing values?
- How to check if two data frames same or not in R?
- How to find the correlation coefficient between two data frames in R?
- How to randomly replace values in an R data frame column?

Advertisements