Created
August 17, 2016 18:51
-
-
Save gluc/1176a4240554e4db5204dd229c8505ce to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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