Aggregate {data.tree} | R Documentation |
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 |
attribute |
determines what is collected. The
|
aggFun |
the aggregation function to be applied to the children's |
... |
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