Skip to content

Instantly share code, notes, and snippets.

@symbolrush
Last active May 16, 2018 15:16
Show Gist options
  • Save symbolrush/d8ccb7724a69a809586bb02da7bf9fe8 to your computer and use it in GitHub Desktop.
Save symbolrush/d8ccb7724a69a809586bb02da7bf9fe8 to your computer and use it in GitHub Desktop.
rule engine - first shot
imsbasics::clc()
apply_rules <- function(data, rules) {
for (i in 1:length(rules)) {
rules_now <- unlist(strsplit(rules[i], ", "))
for (j in 1:length(rules_now)) {
data[i] <- apply_rule(data[i], rules_now[j])
}
}
return(data)
}
apply_rule <- function(data, rule) {
rule <- get(rule)
data <- rule(data)
return(data)
}
rule1 <- function(data) {
data * 2
}
rule2 <- function(data) {
data + 1
}
rule3 <- function(data) {
data ^ 3
}
# Interaktive Tests, einzelne Rules, gepiped.
library(magrittr)
data <- c(1,2,3)
apply_rule(data, "rule1")
apply_rule(data, "rule1") %>% apply_rule("rule2")
apply_rule(data, "rule2") %>% apply_rule("rule1")
apply_rule(data, "rule3")
apply_rule(data, "rule3") %>% apply_rule("rule2") %>% apply_rule("rule1")
# Hinterlegung der Rules für jedes Element, automatisches dispatching mit apply_rules()
df <- data.frame(
data <- c(1,2,3),
rules <- c("rule1", "rule1, rule2, rule3", "rule3, rule2"),
stringsAsFactors = FALSE
)
apply_rules(df$data, df$rules)
# [1] 2 125 28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment