Home > other >  Unnest a list-column of tibbles with different data type (cannot combine double and character)
Unnest a list-column of tibbles with different data type (cannot combine double and character)

Time:11-04

I would like to unnest a nested tibble, however, I get an error.

Example data:

library(tidyverse)

df <- tribble(
  ~x, ~y,
  1,  tibble(a=1,   b=2),
  2,  tibble(a=4:5, b=c("thank","you"),c=1:2))

df
#> # A tibble: 2 x 2
#>       x y               
#>   <dbl> <list>          
#> 1     1 <tibble [1 x 2]>
#> 2     2 <tibble [2 x 3]>

df %>% unnest(y)
#> Error: Can't combine `..1$b` <double> and `..2$b` <character>.

Created on 2021-11-03 by the reprex package (v2.0.1)

I think I have to change the data type of all tibbles listed in y to character, but I got stuck with that.

CodePudding user response:

Maybe the following?

library(tidyverse)

df <- tribble(
  ~x, ~y,
  1,  tibble(a=1,   b=2),
  2,  tibble(a=4:5, b=c("thank","you"),c=1:2))

df %>% 
  mutate(y = map(y, ~ mutate(.x, b = as.character(b)))) %>%
  unnest(cols = c(y))

#> # A tibble: 3 × 4
#>       x     a b         c
#>   <dbl> <dbl> <chr> <int>
#> 1     1     1 2        NA
#> 2     2     4 thank     1
#> 3     2     5 you       2

CodePudding user response:

There might be a more elegant way but this works. Turn the tribble into characters and then you can combine. You can most likely just change column 'b' to the same class and it will be fine.

library(tidyverse)

df <- tribble(
  ~x, ~y,
  1,  tibble(a=1,   b=2),
  2,  tibble(a=4:5, b=c("thank","you"),c=1:2))




df$y[[1]] <- purrr::map_df(df$y[[1]], as.character)

df$y[[2]] <- purrr::map_df(df$y[[2]], as.character)

df %>% unnest(y)

Starting with the original data all you really need to do is change the class of b in the first nested tibble to character.

df$y[[1]]$b <- as.character(df$y[[1]]$b )


df %>% unnest(y)
  • Related