as_flat_list: Convert to a flat list

as_flat_listR Documentation

Convert to a flat list

Description

Recursively flattens a list. Unlike the similar unlist(), it

  • always returns a 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.

  • removes list names. unlist() concatenates nested names (separated by a dot).

Usage

as_flat_list(x, keep_attrs = TRUE, attrs_to_drop = "xfun_strict_list")

Arguments

x

An R object.

keep_attrs

Keep attributes (and thereby retain list structure of custom objects). A logical scalar.

attrs_to_drop

Attribute names which should never be kept. Only relevant if keep_attrs = TRUE. A character vector.

Value

A list.

Examples

library(magrittr)

nested_list <- list(1:3, list("foo", list("bar"))) %T>% str()

# unlike `unlist()` which also removes the last list tier in many cases...
unlist("foobar")
unlist(nested_list) |> str()
# ...this function always returns an (unnested) list
pal::as_flat_list("foobar") |> str()
pal::as_flat_list(nested_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, attributes and thus custom objects (except `xfun_strict_list`) 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, keep_attrs = FALSE) |> str()
# ...or retain `xfun_strict_list`s, too
pal::as_flat_list(nested_list_2, attrs_to_drop = NULL) |> str()

salim-b/pal documentation built on Feb. 28, 2025, 6:51 p.m.