Search code examples
rfor-loopformula

R apply a formula in a for loop


I would like to create a function in which a mathematical formula is set as argument (with only two possible variables) and use this formula within two nested loop. The idea is to be able to change the formula as I would like to create y values based on the formula. This is what I have done but I cannot apply the formula:

foo <- function(formula = y~a-b){
formula = as.formula(y ~a -b)
formula = formula[[3:length(formula)]]
result = NULL
for (a in 1:30) {
 for(b in 1:30){
  result = c(result, noquote(formula))
 }
}
return(result)
}

Solution

  • Create a template fun and then insert the formula into its body.

    foo <- function(formula = y ~ a - b) {
      fun <- function(a, b) {}
      body(fun) <- formula[[length(formula)]]
      result <- NULL
      for (a in 1:30) {
        for(b in 1:30) {
          result = c(result, fun(a, b))
        }
      }
      return(result)
    }
    
    # test
    result <- foo()