Skip to content

Instantly share code, notes, and snippets.

@gluc
Created August 17, 2016 18:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gluc/1176a4240554e4db5204dd229c8505ce to your computer and use it in GitHub Desktop.
Save gluc/1176a4240554e4db5204dd229c8505ce to your computer and use it in GitHub Desktop.
library(data.tree)
library(yaml)
yaml <- "
node1:
value: 2
fnct: >
function(x) {
2 * x
}
node2:
value: 6
# can be named if you prefer, though that will have no impact
fnct: >
DoCalculate <- function(node) {
node$value * 2
}
"
lol <- yaml.load(yaml)
tree <- as.Node(lol)
evaluator <- function(node) node$fnct <- eval(parse(text = node$fnct))
tree$Do(fun = evaluator,
filterFun = function(node) !is.null(node$fnct))
tree$node1$fnct(5)
tree$node2$fnct(tree$node2)
# if you want to reference an enclosing node from within your function, you can define the functions
# having a node argument, and do a slightly more complex evaluator function. e.g.
yaml <- "
node1:
value: 2
fnct: >
function(node) {
2 * node$value
}
node2:
value: 5
fnct: >
function(node) {
node$value ^ 2
}
"
lol <- yaml.load(yaml)
tree <- as.Node(lol)
evaluator <- function(node) {
f <- eval(parse(text = node$fnct))
# warp the function and call using node
f2 <- function() {
f(node)
}
node$fnct <- f2
}
tree$Do(fun = evaluator,
filterFun = function(node) !is.null(node$fnct))
tree$node1$fnct()
tree$node2$fnct()
Aggregate(tree, "fnct", sum)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment