John-Henry
John-Henry

Reputation: 1807

How do I `unnest` two incompatible nested tibble columns?

I have a column of nested tibbles. I'd like to transform the x value of the second row into a list so that I can unnest. How can I change the values of this nested list conditional on the column name (x) and it's format (character)?

tibble(data = c(tibble(x = list(NULL)), 
                 tibble(x = ""))) %>% 
  unnest(data)
#> Error: Can't combine `..1$data` <list> and `..2$data` <character>.

Upvotes: 2

Views: 1251

Answers (3)

Nir Graham
Nir Graham

Reputation: 5137

library(dplyr)
library(tidyr)

tibble(data = c(
  tibble(x = list(NULL)),
  tibble(x = "")
)) |>
  mutate(data = ifelse(is.list(data),
    data,
    list(data)
  )) |>
  unnest(data)

Upvotes: 1

Julian
Julian

Reputation: 31

in a tibble where a specific column contains "character" and "list" entries try this: lapply(column1, function(x) {if (is.list(x)) x else list(x)})

Upvotes: 0

Tea Tree
Tea Tree

Reputation: 984

@Duck's comment worked for me.

library(dplyr)
library(tidyr)
tibble(data = c(tibble(x = list(NULL)), tibble(x = ""))) %>% 
unnest_wider(data)

Let me try to explain:

tidy::unnest() struggles to unnest tibbles that have more than one level of nesting. Unnest_wider is capable of "rectangling" which the tidyverse website describes as "the art and craft of taking a deeply nested list (often sourced from wild caught JSON or XML) and taming it into a tidy data set of rows and columns."

Unnest_wider takes each element of a list-column and makes a new column.

Upvotes: 3

Related Questions