I have a dataframe with a set of objects df$data
and a set of rules to be applied on every object df$rules
.
df <- data.frame(
data = c(1,2,3),
rules = c("rule1", "rule1, rule2, rule3", "rule3, rule2"),
stringsAsFactors = FALSE
)
The rules are
rule1 <- function(data) {
data * 2
}
rule2 <- function(data) {
data + 1
}
rule3 <- function(data) {
data ^ 3
}
For every row in the dataframe I want to apply all the rules specified in the rules
column. The rules should be applied in series.
What I figured out:
apply_rules <- function(data, rules) {
for (i in 1:length(data)) {
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) {
return(sapply(data, rule))
}
apply_rules(df$data, df$rules)
# [1] 2 125 28
Although this works I'm pretty sure there must be more elegant solutions. On SO I could find lot's of stuff about the apply
-functions and also one post about applying many functions to a vector and something about chaining functions. The Compose
idea looks promising but I couldn't figure out how to make a call to Compose
with my rules as string. (parse()
didn't work..)
Any hints?