Learn R Programming

data.tree (version 0.1.6)

Get: Traverse a Tree and Collect Values

Description

The Get function is one of the most important ones of the data.tree package. It lets you traverse a tree and collect values along the way. Alternatively, you can call a method or a function on each Node.

Usage

Get(attribute, ..., traversal = "pre-order", filterFun = function(x) TRUE,
  assign = NULL, format = NULL)

Arguments

attribute
determines what is collected during traversal. The attribute can be
  • a.) the name of a field of eachNodein the tree
  • b.) the name of a Method of eachNode.
  • c.) a function, whose first argument must be a
traversal
determines the traversal order. It can be either "pre-order", "post-order", or "ancestor"
filterFun
allows providing a a filter, i.e. a function taking a Node as an input, and returning TRUE or FALSE. Note that if filter returns FALSE, then the node and its entire subtree are ignored and neither traver
assign
can be the name of a variable to which we assign the collected values before format is called.
format
can be a function that transforms the collected values, e.g. for printing

Value

  • a vector containing the atrributes collected during traversal, in traversal order. NULL is converted to NA, such that length(Node$Get) == Node$totalCount

See Also

Node

Examples

Run this code
data(acme)
acme$Get("level")
acme$Get("totalCount")

calculateAggregateChildCost <- function(node, fun) {
 if (node$isLeaf) return(node$cost)
 fun(sapply(node$children, function(x) x$averageCost))
}

myFormat <- function(x) {
 format(x, nsmall=2, scientific = FALSE)
}

acme$Get(calculateAggregateChildCost,
        mean,
        traversal = "post-order",
        assign = "averageCost",
        format = myFormat)

Run the code above in your browser using DataLab