create account

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

View this thread on: hive.blogpeakd.comecency.com
· @snippets ·
$0.13
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](https://files.peakd.com/file/peakd-hive/snippets/23tSzLNbpN54RvCEy8HyEfmWuv1eDABAseRmCPUkYzra8ooTAwAhA6wLUdSXjUaHzAZm3.png)


![snippets.png](https://files.peakd.com/file/peakd-hive/snippets/AKNMuVqPrNWuLjdyxwLdzm99obv1dcnZWufeJdBoWwecd9UBvGxERepophy4Epu.png)
👍  , , , , , ,
properties (23)
authorsnippets
permlinkr-merging-two-data-frames-such-that-all-the-records-are-included
categoryhive-138200
json_metadata{"app":"peakd/2023.9.2","format":"markdown","tags":["coding","programming","development","proofofbrain","stemgeeks","datascience","rstats","r"],"users":[],"image":["https://files.peakd.com/file/peakd-hive/snippets/AKNMuVqPrNWuLjdyxwLdzm99obv1dcnZWufeJdBoWwecd9UBvGxERepophy4Epu.png","https://files.peakd.com/file/peakd-hive/snippets/23tSzLNbpN54RvCEy8HyEfmWuv1eDABAseRmCPUkYzra8ooTAwAhA6wLUdSXjUaHzAZm3.png"]}
created2023-10-10 02:09:51
last_update2023-10-10 02:09:51
depth0
children0
last_payout2023-10-17 02:09:51
cashout_time1969-12-31 23:59:59
total_payout_value0.064 HBD
curator_payout_value0.063 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,219
author_reputation801,725,525,485
root_title"R: Merging two data frames such that all the records are included"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd0
post_id127,854,822
net_rshares316,216,521,337
author_curate_reward""
vote details (7)