Learn R Programming

data.tree (version 0.2.0-3)

Aggregate: Aggregate child values of a Node, standalone or in traversal.

Description

The Aggregate method lets you fetch an attribute from a Node's children, and then aggregate it. 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, cacheAttribute = NULL, ...)

Arguments

node

the Node on which to aggregate

attribute

determines what is collected. The attribute can be

  • a.) the name of a field of each Node in the tree

  • b.) the name of a method of each Node in the tree

  • c.) a function, whose first argument must be a Node

aggFun

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

cacheAttribute

the name to which results should be stored, if any (NULL otherwise). If not NULL, then the function checks whether this attribute is set, and only evaluates attribute if it is not. If used wisely in connection with post-order traversal, this parameter allows to speed up calculation by breaking recursion.

...

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 it is a field, and if the node contains the attribute, its value is returned. Otherwise, aggFun(Aggregate(children, ...)) is called. In that case, the attribute must be set on the leaf.

See Also

Node

Examples

Run this code
# NOT RUN {
data(acme)

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

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

#use Aggregate with caching:
acme$cost
acme$Do(function(x) Aggregate(x, "cost", sum, cacheAttribute = "cost"), traversal = "post-order")
acme$cost

#use Aggregate with a function:
acme$Do(function(x) x$expectedCost <- Aggregate(x,
                                                function(x) x$cost * x$p,
                                                sum)
       , traversal = "post-order")
# }

Run the code above in your browser using DataLab