nest_tree: Convert a data frame to a tree

View source: R/nest_tree.R

nest_treeR Documentation

Convert a data frame to a tree

Description

Recursively nest data frame rows based on parent-child relationships, defined by an id column and a parent column. Children become sub-tibbles of their parent rows. This structure is intended for representing tree-like data, such as organizational charts, file systems, category trees, or any other hierarchical relationships.

Usage

nest_tree(x, id_col, parent_col, children_to)

Arguments

x

(data.frame) The data frame to nest.

id_col

(character(1), integer(1), or symbol) The column that uniquely identifies each observation.

parent_col

(character(1), integer(1), or symbol) The column that identifies the parent id of each observation. Each value must either be missing (for the root elements) or appear in the id_col column.

children_to

(character(1)) The column name in which to store the children.

Value

A tree-like, recursively nested data frame.

Examples

df <- tibble::tibble(
  id = 1:5,
  x = letters[1:5],
  parent = c(NA, NA, 1L, 2L, 4L)
)
df

# Only the root elements are in the top-level tibble.
out <- nest_tree(df, id, parent, "children")
out

# The children of each element are stored in the "children" column.
out$children

# "d" (id 4) is a child of "b" (id 2), and "e" (id 5) is a child of "d"
# (id 4).
out$children[[2]]$children

tibblify documentation built on May 9, 2026, 5:07 p.m.