Maybe the dataframe merge?

Hi,
I met another interesting question when practicing with R. I just want to combine D1 and D2, to get the dataframe like D3 that have full information. It seems that some function about"join" doesn't work.(I know D1[1,2]<-3 is right. But we may met many data in other case. Here just an example data). Thank you for help in advance.

c1<-c(2,6)
c2<-c(NA,5)
D1<-data.frame(c1,c2)

c3<-c(NA,NA)
c4<-c(3,NA)
D2<-data.frame(c3,c4)

C5<-(2,6)
C6<-(3,5)
D3<-data.frame(c5,c6)

Created on 2023-05-28 with reprex v2.0.2

I think the coalesce() function does what you want.

c1<-c(2,6)
c2<-c(NA,5)
D1<-data.frame(c1,c2)

c3<-c(NA,NA)
c4<-c(3,NA)
D2<-data.frame(c3,c4)

C5 <- c(2,6)
C6 <- c(3,5)
D3 <- data.frame(C5,C6)
D1
#>   c1 c2
#> 1  2 NA
#> 2  6  5
D2
#>   c3 c4
#> 1 NA  3
#> 2 NA NA
D3
#>   C5 C6
#> 1  2  3
#> 2  6  5
library(purrr)
library(dplyr)

D4 <- map2_dfc(D1, D2, ~coalesce(.x, .y))
D4
#> # A tibble: 2 × 2
#>      c1    c2
#>   <dbl> <dbl>
#> 1     2     3
#> 2     6     5

Created on 2023-05-28 with reprex v2.0.2

1 Like

This topic was automatically closed 7 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.