Search code examples
rdplyrtidyrdata-manipulationtidy

bind_rows in a list even though the class() is different


I have a list below what I don't wanna do is to change the class(Category) in df2. The code should change the class(category) and assign it category in the list() object. How to get around this? Many thanks in advance.

df1 <- data_frame(ID = paste0(LETTERS[1],1:4), valueA = seq(0.1,0.4,0.1), Category= "Apples" )
df2 <- data_frame(ID = paste0(LETTERS[1],5:8), valueB = seq(0.1,0.4,0.1),  Category= seq(0.1,0.4,0.1))
df3 <- data_frame(ID = paste0(LETTERS[1],9:12), valueC = seq(0.1,0.4,0.1),  Category= "Apples3")

list1 <- list(df1, df2, df3);list1
bind_rows(list1)

Error in `bind_rows()`:
! Can't combine `..1$Category` <character> and `..2$Category` <double>.
Run `rlang::last_trace()` to see where the error occurred.

Solution

  • We could convert all the columns to character and then automatically change the type with type.convert

    library(purrr)
    library(dplyr)
     map_dfr(list1, ~ .x %>% 
      mutate(across(everything(), as.character))) %>% 
      type.convert(as.is= TRUE)
    

    -output

    # A tibble: 12 × 5
       ID    valueA Category valueB valueC
       <chr>  <dbl> <chr>     <dbl>  <dbl>
     1 A1       0.1 Apples     NA     NA  
     2 A2       0.2 Apples     NA     NA  
     3 A3       0.3 Apples     NA     NA  
     4 A4       0.4 Apples     NA     NA  
     5 A5      NA   0.1         0.1   NA  
     6 A6      NA   0.2         0.2   NA  
     7 A7      NA   0.3         0.3   NA  
     8 A8      NA   0.4         0.4   NA  
     9 A9      NA   Apples3    NA      0.1
    10 A10     NA   Apples3    NA      0.2
    11 A11     NA   Apples3    NA      0.3
    12 A12     NA   Apples3    NA      0.4
    

    Or we could nest it

    map_dfr(list1, ~ .x %>% nest(data = Category))
    

    -output

    # A tibble: 12 × 5
       ID    valueA data             valueB valueC
       <chr>  <dbl> <list>            <dbl>  <dbl>
     1 A1       0.1 <tibble [1 × 1]>   NA     NA  
     2 A2       0.2 <tibble [1 × 1]>   NA     NA  
     3 A3       0.3 <tibble [1 × 1]>   NA     NA  
     4 A4       0.4 <tibble [1 × 1]>   NA     NA  
     5 A5      NA   <tibble [1 × 1]>    0.1   NA  
     6 A6      NA   <tibble [1 × 1]>    0.2   NA  
     7 A7      NA   <tibble [1 × 1]>    0.3   NA  
     8 A8      NA   <tibble [1 × 1]>    0.4   NA  
     9 A9      NA   <tibble [1 × 1]>   NA      0.1
    10 A10     NA   <tibble [1 × 1]>   NA      0.2
    11 A11     NA   <tibble [1 × 1]>   NA      0.3
    12 A12     NA   <tibble [1 × 1]>   NA      0.4