Learn R Programming

data.tree (version 0.2.0-3)

Get: Traverse a Tree and Collect Values

Description

The Get method 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(nodes, attribute, ..., format = NULL, inheritFromAncestors = FALSE,
  simplify = c(TRUE, FALSE, "array", "regular"))

Arguments

nodes

The nodes on which to perform the Get (e.g. obtained via Traverse

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

...

in case the attribute is a function or a method, the ellipsis is passed to it as additional arguments.

format

can be a function that transforms the collected values, e.g. for printing

inheritFromAncestors

if TRUE, then the path above a Node is searched to get the attribute in case it is NULL.

simplify

same as sapply, i.e. TRUE, FALSE or "array". Additionally, you can sepcify "regular" if each returned value is of length > 1, and equally named. See below for an example.

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

Set

Examples

Run this code
# NOT RUN {
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",
        format = myFormat)

#simplify = "regular" will preserve names
acme$Get(function(x) c(position = x$position, level = x$level), simplify = "regular")
# }

Run the code above in your browser using DataLab