Search code examples
rdplyrtidyverse

unnest_longer column with char and list entries


I am trying to convert JSON file to tibble. First I combine all list entries of the JSON file to a tibble that looks like this:

df <- tibble(none_nested = c("a", "b", "c"), 
             all_nested = c(list(list("a", "b")), list(list("a", "b")), list(list("a", "b"))), 
             some_nested = c("a", "b", list(list("a", "b")))
             )

The problem is that I cannot call unnest_longer on some_nested.

unnest_longer(df, some_nested)

-> 
Error in `col_to_long()`:
! Can't combine `..1$some_nested` <character> and `..4$some_nested` <list>.

Solution

  • In the some_nested column, some rows are not in the list (first and second rows are in char) so you couldn't use the unnest_longer.

    below code should work

    df |> 
      mutate(some_nested = map(some_nested, ~if(is.list(.x)) .x else list(.x))) |> 
      unnest_longer(some_nested)