as_flat_list | R Documentation |
Recursively flattens an R object. Unlike base::unlist()
, it
always returns a regular list, i.e. wraps x
in a list if necessary, and will never remove the last list level. Thus it is
type-safe.
won't treat any of the list leafs specially (like unlist()
does with factors). Thus leaf values will never be modified.
as_flat_list(
x,
is_node = NULL,
name_spec = "{outer}.{inner}",
name_repair = c("minimal", "unique", "check_unique", "universal")
)
x |
An R object. |
is_node |
A predicate function that determines whether an element is
a node (by returning |
name_spec |
If both inner and outer names are present, control
how they are combined. Should be a glue specification that uses
variables |
name_repair |
One of |
A list.
library(magrittr)
nested_list <- list(1:3, list("foo", list("bar"))) %T>% str()
lm_obj <- lm(mpg ~ hp, mtcars)
# unlike `unlist()` which also removes the last list tier from regular lists and many list-based
# objects...
unlist("foobar")
unlist(nested_list) |> str()
unlist(lm_obj) |> str()
# ...this function is able to return consistent results, i.e. an unnested list
pal::as_flat_list("foobar", is_node = is.list) |> str()
pal::as_flat_list(nested_list, is_node = is.list) |> str()
pal::as_flat_list(lm_obj, is_node = is.list) |> str()
nested_list <- list(list(factor("a"), factor("b")), factor("c")) %T>% str()
# unlike `unlist()` which combines factors...
unlist(nested_list) |> str()
# ...this function does not modify the list elements
pal::as_flat_list(nested_list) |> str()
nested_list <-
list(c(list(1L), list(tibble::tibble(a = list(1.1, "2")))),
list(tibble::as_tibble(mtcars[1:2, ]))) %T>%
str()
nested_list_2 <- list(1:3, xfun::strict_list(list(list("buried deep")))) %T>% str()
# by default, classed lists like data frames, tibbles or `xfun_strict_list`s are retained, i.e.
# not flattened...
pal::as_flat_list(nested_list) |> str()
pal::as_flat_list(nested_list_2) |> str()
# ...but you can drop them and thereby flatten custom objects if needed
pal::as_flat_list(nested_list, is_node = is.list) |> str()
pal::as_flat_list(nested_list_2, is_node = is.list) |> str()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.