Home > OS >  Fill na column of 2nd dataframe with 1st dataframe which are matching in R
Fill na column of 2nd dataframe with 1st dataframe which are matching in R

Time:11-26

DF1 = data.frame(A=c("cats","dogs","pig"), B=c("kittens","puppies","pig"),C=c("dog","cat","mouse"))

DF2 = data.frame( A=c("cats","dogs","pig"), B=c("kittens",NA,NA))

The 2nd DF2 has NA column but i need to replace NA with pig row of 1st column. It should match the row of NA with the row of DF1 and replace accordingly. I have tried with merge but it doesn't work.

CodePudding user response:

library(dplyr)
DF2 |> 
  rows_update(DF1, by = "A")

     A       B
1 cats kittens
2 dogs puppies
3  pig     pig

UPDATE: a solution in case the joining data frames have different columns:

DF1 <- tibble(A = c("cats","dogs","pig"),
              B = c("kittens","puppies","pig"),
              C = c(1:3))

DF2 <- data.frame(A = c("cats","dogs","pig"),
                  B = c("kittens","puppies",NA))

DF2 |> 
  rows_update(DF1 |> select(any_of(names(DF2))),
              by = "A")
  •  Tags:  
  • r
  • Related