Merge Dataframes to Fill Missing Data in RStudio

Hello,

Looking for assistance with merging data frames in RStudio. I have had a look online but haven't come across this particular scenario.

I have 2 dataframes:

  1. x y
    a A1 blue
    b A2 N/A
    c A3 yellow

  2. x y
    a A1 N/A
    b A2 red
    c A3 N/A

this is the output I want:

  1. x y
    a A1 blue
    b A2 red
    c A3 yellow

I've tried a few packages but they only seem to try and add extra columns or rows. I just want to fill in those blanks by merging the dataframes. I hope there is an easy way to do this... there is in excel, but that's too slow.

Thanks in advance for your patience with my novice question.

Cheers

You can use dplyr::rows_update() function, is similar to using UPDATED in SQL

Thanks for your help.. I'm still working out how to do it. I am getting the error "x` key values are not unique."
I tried: rows_update(df1, df2, by = "y")
and same with rows_patch.
Not sure if something incompatible with my data or my mistake coding?

The key column is "x" so you should update by "x", if you also have NA in "x", then filter NAs from the key column before updating

Now that I have a little time I can give you a reproducible example (reprex)

library(dplyr)

# Sample data in a copy/paste friendly format, replace these with your own data frames 
df1 <- data.frame(
  stringsAsFactors = FALSE,
                 x = c("A1", "A2", "A3"),
                 y = c("blue", NA, "yellow")
)

df2 <- data.frame(
  stringsAsFactors = FALSE,
                 x = c("A1", "A2", "A3"),
                 y = c(NA, "red", NA)
)

# Relevant code
df1 %>%
    rows_update(df2 %>% filter(!is.na(y)), by = "x")
#>    x      y
#> 1 A1   blue
#> 2 A2    red
#> 3 A3 yellow

Note: Next time please provide a proper REPRoducible EXample (reprex) illustrating your issue.

Thanks so much for your time, that has helped

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.