hier_grid: Compute a grid given different hierarchies

View source: R/hier_grid.R

hier_gridR Documentation

Compute a grid given different hierarchies

Description

This function returns a data.table containing all possible combinations of codes from one or more hierarchy objects. This is useful to compute "complete" tables for SDC purposes.

Usage

hier_grid(
  ...,
  add_dups = TRUE,
  add_levs = FALSE,
  add_default_codes = FALSE,
  add_contributing_cells = FALSE
)

Arguments

...

one or more hierarchy objects created with hier_create() or hier_compute()

add_dups

scalar logical defining if bogus codes (parents with only one child and no siblings) should be included. If FALSE, these parents are removed and replaced by their most granular leaf.

add_levs

scalar logical defining if numerical levels for each code should be appended to the output.

add_default_codes

scalar logical defining if standardized level codes should be additionally returned.

add_contributing_cells

logical: if TRUE, two columns are added: leaf_id (a unique integer for terminal leaf combinations) and contributing_leaf_ids (a list-column of integers representing all terminal leaves contributing to that cell).

Value

a data.table featuring:

  • ⁠v{n}⁠: columns for each hierarchy object.

  • cell_id: a unique string identifier created by concatenating default codes.

  • ⁠levs_v{n}⁠: (optional) numerical hierarchy levels.

  • ⁠default_v{n}⁠: (optional) standardized level codes.

  • leaf_id: (optional) unique integer for base/terminal cells.

  • contributing_leaf_ids: (optional) integer vectors for aggregation.

Examples

# Define hierarchies with some "bogus" codes
h1 <- hier_create("Total", nodes = LETTERS[1:3])
h1 <- hier_add(h1, root = "A", node = "a1")
h1 <- hier_add(h1, root = "a1", node = "aa1")

h2 <- hier_create("Total", letters[1:5])
h2 <- hier_add(h2, root = "b", node = "b1")
h2 <- hier_add(h2, root = "d", node = "d1")

# Standard grid with all codes
hier_grid(h1, h2)

# Grid without bogus codes
# h1: `A` and `a1` are replaced by `aa1`
# h2: `b` and `d` are replaced by `b1` and `d1`
# This ensures the grid is consistent with the most granular data.
hier_grid(h1, h2, add_dups = FALSE)

# Advanced grid with contributing indices
# The 'cell_id' will be a concatenated string like '0000000'
# The 'contributing_leaf_ids' column allows for high-speed aggregation
# and/or matching with micro-data (for an example see `?hier_create_ids()`)
hier_grid(h1, h2,
  add_dups = FALSE,
  add_contributing_cells = TRUE
)

sdcHierarchies documentation built on March 20, 2026, 1:06 a.m.