Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

Aggregate

Aggregate child values of a Node, recursively.


Description

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.

Usage

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

Arguments

node

the Node on which to aggregate

attribute

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)

aggFun

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)

Details

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

Examples

data(acme)

#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)
  }))
}
HomeRolledAggregate(acme)

#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")
acme$IT$cost

data.tree

General Purpose Hierarchical Data Structure

v1.0.0
GPL (>= 2)
Authors
Russ Hyde [ctb] (improve dependencies), Chris Hammill [ctb] (improve getting), Facundo Munoz [ctb] (improve list conversion), Markus Wamser [ctb] (fixed some typos), Pierre Formont [ctb] (additional features), Kent Russel [ctb] (documentation), Noam Ross [ctb] (fixes), Duncan Garmonsway [ctb] (fixes), Christoph Glur [aut, cre] (R interface)
Initial release
2020-07-31

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.