snippets avatar

R: Merging two data frames such that all the records are included

snippets

Published: 10 Oct 2023 › Updated: 10 Oct 2023R: Merging two data frames such that all the records are included

R: Merging two data frames such that all the records are included

This is a problem of merging two data frames such that all the records are included. The approach used is Tidyverse

I have two data frames, df1 and df2 that look as follows.

df1 <- data.frame(
A = c(1, 2, 3, 4, 5, 6, 7, 8, 9),
B = c("a", "b", "c", "d", "e", "f", "g", "h", "i"))

df2 <- data.frame(
A = c(1, 2, 11),
C = c("as", "ba", "js"))

I want to merge the two data frames into a new one, and make sure that in column A, all cases (i.e, 1 to 11) are included. I want the contents of both B and C to be included too.

This is the code that ultilize full_join() to merge the dataframes, with pipe operation.

result <- df1 %>% #Put in df1
full_join(df2, by = "A") %>% #Join it with df2,and by what is in A
complete(A = 1:11) %>% # complete() adds rows for missing values in A
replace_na(list(B = "N/A", C = "N/A")) # finally replace NAs with "N/A"
print(result) # Display results

Screenshot 2023-10-10 at 10.05.10 AM.png

snippets.png

Leave R: Merging two data frames such that all the records are included to:

Written by

A place for code snippets and everything else on programming that are useful.

Read more #coding posts


Best Posts From snippets

We have not curated any of snippets's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From snippets