as_flat_list: Convert to flat list

as_flat_listR Documentation

Convert to flat list

Description

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.

Usage

as_flat_list(
  x,
  is_node = NULL,
  name_spec = "{outer}.{inner}",
  name_repair = c("minimal", "unique", "check_unique", "universal")
)

Arguments

x

An R object.

is_node

A predicate function that determines whether an element is a node (by returning TRUE) or a leaf (by returning FALSE). The default value, NULL, treats simple lists as nodes and everything else (including richer objects like data frames and linear models) as leaves, using vctrs::obj_is_list(). To recurse into all objects built on lists use is.list().

name_spec

If both inner and outer names are present, control how they are combined. Should be a glue specification that uses variables inner and outer.

name_repair

One of "minimal", "unique", "universal", or "check_unique". See vctrs::vec_as_names() for the meaning of these options.

Value

A list.

Examples

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()

salim-b/pal documentation built on June 9, 2025, 12:39 a.m.