Skip to content

Instantly share code, notes, and snippets.

@gluc
Last active October 4, 2015 11:36
Show Gist options
  • Save gluc/bbd9b9d38baf2475ecf2 to your computer and use it in GitHub Desktop.
Save gluc/bbd9b9d38baf2475ecf2 to your computer and use it in GitHub Desktop.
data.tree YAML function
This demonstrates how to add functions to a YAML.
Remainder <- function(self) {
1 - sum( Get(self$siblings, "p"))
}
name: Jenny Lind
type: decision
Sign with Movie Company:
type: chance
Small Box Office:
type: terminal
p: 0.3
payoff: 200000
Medium Box Office:
type: terminal
p: 0.6
payoff: 1000000
Large Box Office:
type: terminal
p: "function:Remainder"
payoff: 3000000
Sign with TV Network:
type: chance
Small Box Office:
type: terminal
p: 0.3
payoff: 900000
Medium Box Office:
type: terminal
p: 0.6
payoff: 900000
Large Box Office:
type: terminal
p: "function:Remainder"
payoff: 900000
#requires data.tree 0.2.2
library(data.tree)
library(yaml)
library(stringr)
fileName <- 'jennylind.yaml'
l <- yaml.load_file(fileName)
jl <- as.Node(l)
#this file contains all the functions referred to from the yaml
source("functions.R")
#function to replace the function tags with their actual functions
ReplaceFunction <- function(x) {
for( field in x$fields) {
if (str_detect(x[[field]], "function[:][:alpha:]+")) {
functionName <- str_sub(x[[field]], str_locate(x[[field]], ":")[1, 1] + 1)
x[[field]] <- eval(parse(text = functionName))
}
}
}
#actually do the replacement
jl$Do(ReplaceFunction)
print(jl, "p")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment