Reputation: 1807
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
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
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
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