Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)

I have two data.frames, one with only characters and the other one with characters and values.

df1 = data.frame(x=c('a', 'b', 'c', 'd', 'e'))

df2 = data.frame(x=c('a', 'b', 'c'),y = c(0,1,0))

merge(df1, df2)

  x y

1 a 0

2 b 1

3 c 0 

I want to merge df1 and df2. The characters a, b and c merged good and also have 0, 1, 0 but d and e have nothing. I want d and e also in the merge table, with the 0 0 conditions. Thus for every missing row at the df2 data.frame, the 0 must be placed in the df1 table, like:

  x y

1 a 0

2 b 1

3 c 0

4 d 0

5 e 0

1 Answer

0 votes
by
edited

To merge unequal data frames using merge function, you need to set the all argument of the merge function to TRUE to return NA for values that do not match.i.e.,

df1 = data.frame(x=c('a', 'b', 'c', 'd', 'e'))

df2 = data.frame(x=c('a', 'b', 'c'),y = c(0,1,0))

df <- merge(df1, df2, all = TRUE)

df[is.na(df)] <- 0  #To set NA to zero

df

  x y

1 a 0

2 b 1

3 c 0

4 d 0

5 e 0

If you want to learn more about R programming watch this tutorial on Introduction to Data Science with R 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...