unnest_wider | R Documentation |
unnest_wider()
turns each element of a list-column into a column. It
is most naturally suited to list-columns where every element is named,
and the names are consistent from row-to-row.
unnest_wider()
preserves the rows of x
while modifying the columns.
Learn more in vignette("rectangle")
.
unnest_wider(
data,
col,
names_sep = NULL,
simplify = TRUE,
strict = FALSE,
names_repair = "check_unique",
ptype = NULL,
transform = NULL
)
data |
A data frame. |
col |
< When selecting multiple columns, values from the same row will be recycled to their common size. |
names_sep |
If If any values being unnested are unnamed, then |
simplify |
If |
strict |
A single logical specifying whether or not to apply strict
vctrs typing rules. If |
names_repair |
Used to check that output data frame has valid names. Must be one of the following options:
See |
ptype |
Optionally, a named list of prototypes declaring the desired output type of each component. Alternatively, a single empty prototype can be supplied, which will be applied to all components. Use this argument if you want to check that each element has the type you expect when simplifying. If a |
transform |
Optionally, a named list of transformation functions applied to each component. Alternatively, a single function can be supplied, which will be applied to all components. Use this argument if you want to transform or parse individual elements as they are extracted. When both |
Other rectangling:
hoist()
,
unnest_longer()
,
unnest()
df <- tibble(
character = c("Toothless", "Dory"),
metadata = list(
list(
species = "dragon",
color = "black",
films = c(
"How to Train Your Dragon",
"How to Train Your Dragon 2",
"How to Train Your Dragon: The Hidden World"
)
),
list(
species = "blue tang",
color = "blue",
films = c("Finding Nemo", "Finding Dory")
)
)
)
df
# Turn all components of metadata into columns
df %>% unnest_wider(metadata)
# Choose not to simplify list-cols of length-1 elements
df %>% unnest_wider(metadata, simplify = FALSE)
df %>% unnest_wider(metadata, simplify = list(color = FALSE))
# You can also widen unnamed list-cols:
df <- tibble(
x = 1:3,
y = list(NULL, 1:3, 4:5)
)
# but you must supply `names_sep` to do so, which generates automatic names:
df %>% unnest_wider(y, names_sep = "_")
# 0-length elements ---------------------------------------------------------
# The defaults of `unnest_wider()` treat empty types (like `list()`) as `NULL`.
json <- list(
list(x = 1:2, y = 1:2),
list(x = list(), y = 3:4),
list(x = 3L, y = list())
)
df <- tibble(json = json)
df %>%
unnest_wider(json)
# To instead enforce strict vctrs typing rules, use `strict`
df %>%
unnest_wider(json, strict = TRUE)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.