R/hier_add.R

Defines functions hier_add

Documented in hier_add

#' Add nodes to an existing hierarchy
#'
#' This function allows to add nodes (levels)
#' to an existing nested hierarchy.
#'
#' @param tree a (nested) hierarchy created using [hier_create()]
#' or modified using [hier_add()], [hier_delete()] or [hier_rename()].
#' @param root (character) a name of an existing node in the hierarchy
#' @param nodes (character) names of new nodes that should be added below
#' `"root"`
#' @export
#' @md
#' @examples
#' h <- hier_create(root = "Total",  nodes = LETTERS[1:3])
#' h <- hier_add(h, root = "A", nodes = c("a1", "a5"))
#' hier_display(h)
hier_add <- function(tree, root, nodes) {
  .is_valid(tree)
  stopifnot(is_scalar_character(root))

  # rootnode needs to exist in the tree
  if (!.exists(tree = tree, leaf = root)) {
    stop("The root node does not exist!", call. = FALSE)
  }
  stopifnot(is.character(nodes))

  ii <- which(nodes %in% .all_nodes(tree))
  if (sum(ii) > 0) {
    warning("Some of the provided nodes already exist and are not added.")
    nodes <- nodes[!ii]
    if (length(nodes) == 0) {
      return(tree)
    }
  }
  tree <- .add_nodes(
    tree = tree,
    new = data.table(
      root = root,
      leaf = nodes,
      level = tree$level[tree$leaf == root] + 1
    )
  )
  tree <- .add_class(tree)
  .is_valid(tree)
  tree
}

Try the sdcHierarchies package in your browser

Any scripts or data that you put into this service are public.

sdcHierarchies documentation built on Aug. 11, 2023, 1:07 a.m.