Aggregate: Aggregate child values of a 'Node', recursively.

View source: R/node_methods.R

AggregateR Documentation

Aggregate child values of a Node, recursively.


The Aggregate method lets you fetch an attribute from a Node's children, and then aggregate them using aggFun. For example, you can aggregate cost by summing costs of child Nodes. This is especially useful in the context of tree traversal, when using post-order traversal mode.


Aggregate(node, attribute, aggFun, ...)



the Node on which to aggregate


determines what is collected. The attribute can be

  • a.) the name of a field or a property/active of each Node in the tree, e.g. acme$Get("p") or acme$Get("position")

  • b.) the name of a method of each Node in the tree, e.g. acme$Get("levelZeroBased"), where e.g. acme$levelZeroBased <- function() acme$level - 1

  • c.) a function, whose first argument must be a Node e.g. acme$Get(function(node) node$cost * node$p)


the aggregation function to be applied to the children's attributes


any arguments to be passed on to attribute (in case it's a function)


As with Get, the attribute can be a field, a method or a function. If the attribute on a child is NULL, Aggregate is called recursively on its children.

See Also




#Aggregate on a field
Aggregate(acme, "cost", sum)

#This is the same as:
HomeRolledAggregate <- function(node) {
  sum(sapply(node$children, function(child) {
    if (!is.null(child$cost)) child$cost
    else HomeRolledAggregate(child)

#Aggregate using Get
print(acme, "cost", minCost = acme$Get(Aggregate, "cost", min))

#use Aggregate with a function:
Aggregate(acme, function(x) x$cost * x$p, sum)

#cache values along the way
acme$Do(function(x) x$cost <- Aggregate(x, "cost", sum), traversal = "post-order")

data.tree documentation built on Nov. 13, 2023, 1:08 a.m.