'Passing an R expression to a function and then changing its input parameters

I would like to pass an R expression to a self-written function without evaluating it at first and then manipulate an input parameter of the R expression in that function.

I guess, it is easier to explain with an example.

In the below example function fun1, which should take lm(y ~ x, data=datatrain) as an argument without evaluating it at first, I would like to replace datatrain in lm(y ~ x, data=datatrain) by newdatatrain within the function (to be more precise, newdatatrain will be datatrain with some columns permuted within the function).

The reason why I need to provide lm(y ~ x, data=datatrain) as a function argument is that the function should also be able to take other types of models with possibly other input parameters (e.g., randomForest::randomForest(y ~ x, data=datatrain, replace=FALSE)).

Here is what I tried:

# Does not run through:

fun1 <- function(mycall) {
  
  obj <- quote(mycall)
  
  newdatatrain <- data.frame(y=c(0.22,  1.09,  0.93, -0.02, -0.27), 
                             x=c(1.50,  0.53,  0.04, -2.43, -0.54))
  
  obj$data <- newdatatrain
  
  res <- eval(obj)
  
  return(res)
  
}

fun1(lm(y ~ x, data=datatrain))



# Does run through, but is not
# practical, because lm(y ~ x, data=datatrain)
# should be a function argument:


fun2 <- function(mycall) {
  
  obj <- quote(lm(y ~ x, data=datatrain))
  
  newdatatrain <- data.frame(y=c(0.22,  1.09,  0.93, -0.02, -0.27), 
                             x=c(1.50,  0.53,  0.04, -2.43, -0.54))
  
  obj$data <- newdatatrain
  
  res <- eval(obj)
  
  return(res)
  
}

fun2(lm(y ~ x, data=datatrain))

How could this be tackled?



Solution 1:[1]

I'm sorry if I misunderstood, but can you not do something like this:

f <- function(estimator, formula, data) {
  newdata = data[sample(nrow(data),2),]
  predict(estimator(formula,data=data), newdata=newdata)
}

f(lm, y ~ x, datatrain)
f(glm, y ~ x, data=datatrain)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 langtang