Extension about the question"Maybe the dataframe merge?"

Hi, with the help @FJCC , we use the function coalesce we succeed in solving the problem in former post like the following.
Maybe the dataframe merge? - General - Posit Community (rstudio.com)

Recently, new question and thought comes up. When there is character in dataframe, error comes, when practice R.

library(purrr)
library(dplyr)
c1<-c(2,NA)
c2<-c(NA,5)
D1<-data.frame(c1,c2)


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


D4 <- map2_dfc(D1, D2, ~coalesce(.x, .y))
D4

Error in `map2()`:
ℹ In index: 2.
ℹ With name: c2.
Caused by error in `coalesce()`:
! Can't combine `..1` <double> and `..2` <character>.
Run `rlang::last_error()` to see where the error occurred.

What's more, the function coalesce seems works only when two dataframes. If there are more than two dataframes, like the example data, four dataframes. And also have characters. Is there any solution?

c1<-data.frame(a1=c(2,NA,NA),
               a2=c(6,NA,NA),
               a3=c(NA,9,NA))


c2<-data.frame(b1=c(NA,NA,10),
               b2=c(NA,NA,NA),
               b3=c("tree",NA,NA))


c3<-data.frame(c1=c(NA,5.1,NA),
               c2=c(NA,5.6,NA),
               c3=c(NA,NA,NA))


c4<-data.frame(d1=c(NA,NA,NA),
               d2=c(NA,NA,9.2),
               d3=c(NA,NA,88))

Any help would be appreciated!!!

Hi, the first problem is triggered by D1$c2, which is an numeric column, and D2$c4, which is a character column. And you can't combine a character element and a number element in one vector/column.
To solve this, you may unify the format of these columns first before doing the coalesce.
For example, transform the column types into character.

map2_dfc(D1, D2, ~ coalesce(as.character(.x), as.character(.y)))

The latter question can be solved by reduce() from purrr package:

merge_na_df <- function(x, y) {map2_dfc(x, y, ~ coalesce(as.character(.x),as.character(.y)))}

list(c1, c2, c3, c4) %>% reduce(merge_na_df)

you'll get

# A tibble: 3 × 3
  a1    a2    a3   
  <chr> <chr> <chr>
1 2     6     tree 
2 5.1   5.6   9    
3 10    9.2   88   

Information of reduce() can be found at purrr website.

1 Like

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