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.
data(acme)
#Aggregate on a field
Aggregate(acme, "cost", sum)
#> [1] 4950000
#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)
#> [1] 4950000
#Aggregate using Get
print(acme, "cost", minCost = acme$Get(Aggregate, "cost", min))
#> levelName cost minCost
#> 1 Acme Inc. NA 50000
#> 2 ¦--Accounting NA 500000
#> 3 ¦ ¦--New Software 1000000 1000000
#> 4 ¦ °--New Accounting Standards 500000 500000
#> 5 ¦--Research NA 750000
#> 6 ¦ ¦--New Product Line 2000000 2000000
#> 7 ¦ °--New Labs 750000 750000
#> 8 °--IT NA 50000
#> 9 ¦--Outsource 400000 400000
#> 10 ¦--Go agile 250000 250000
#> 11 °--Switch to R 50000 50000
#use Aggregate with a function:
Aggregate(acme, function(x) x$cost * x$p, sum)
#> [1] 2192500
#cache values along the way
acme$Do(function(x) x$cost <- Aggregate(x, "cost", sum), traversal = "post-order")
acme$IT$cost
#> [1] 7e+05