Guest User

Untitled

a guest
May 21st, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. imsbasics::clc()
  2.  
  3. apply_rules <- function(data, rules) {
  4. for (i in 1:length(rules)) {
  5. rules_now <- unlist(strsplit(rules[i], ", "))
  6. for (j in 1:length(rules_now)) {
  7. data[i] <- apply_rule(data[i], rules_now[j])
  8. }
  9. }
  10. return(data)
  11. }
  12.  
  13. apply_rule <- function(data, rule) {
  14. rule <- get(rule)
  15. data <- rule(data)
  16. return(data)
  17. }
  18.  
  19. rule1 <- function(data) {
  20. data * 2
  21. }
  22.  
  23. rule2 <- function(data) {
  24. data + 1
  25. }
  26.  
  27. rule3 <- function(data) {
  28. data ^ 3
  29. }
  30.  
  31. # Interaktive Tests, einzelne Rules, gepiped.
  32. library(magrittr)
  33. data <- c(1,2,3)
  34. apply_rule(data, "rule1")
  35. apply_rule(data, "rule1") %>% apply_rule("rule2")
  36. apply_rule(data, "rule2") %>% apply_rule("rule1")
  37. apply_rule(data, "rule3")
  38. apply_rule(data, "rule3") %>% apply_rule("rule2") %>% apply_rule("rule1")
  39.  
  40. # Hinterlegung der Rules für jedes Element, automatisches dispatching mit apply_rules()
  41. df <- data.frame(
  42. data <- c(1,2,3),
  43. rules <- c("rule1", "rule1, rule2, rule3", "rule3, rule2"),
  44. stringsAsFactors = FALSE
  45. )
  46.  
  47. apply_rules(df$data, df$rules)
  48. # [1] 2 125 28
Add Comment
Please, Sign In to add comment