Skip to contents

The flatten_with_names function recursively traverses a nested list and flattens it into a single-level list. The names of the elements in the resulting list are formed by concatenating the names at each level, separated by dots. This is useful for transforming deeply nested data structures into a flat format suitable for data frames or tibbles.

Usage

flatten_with_names(x, parent_name = "")

Arguments

x

A nested list to be flattened.

parent_name

A character string representing the name prefix from the parent recursion level. Defaults to an empty string.

Value

A named list where each element corresponds to a leaf node in the original nested list, and the names reflect the path to that node.

Examples

if (FALSE) { # \dontrun{
nested_list <- list(
  group = list(
    subgroup = list(
      item1 = 1,
      item2 = 2
    ),
    item3 = 3
  ),
  item4 = 4
)
flatten_with_names(nested_list)
# Expected output:
# $group.subgroup.item1
# [1] 1
#
# $group.subgroup.item2
# [1] 2
#
# $group.item3
# [1] 3
#
# $item4
# [1] 4
} # }