Search code examples
rfunctional-programmingnse

How to build a function with arguments listed as a string vector in R?


How might I write a function that takes a string vector and returns a function with arguments having the names of the string vector? In addition, I'd like to use my string of arguments to make a list or data.frame named with the input columns inside that function. My desired application is to be able to pass this to a predict method for estimating some points. If this function already exists, let me know. Otherwise, I'm curious how I might write it. Below I include R pseudo-code illustrating what I am trying to do and hopefully showing where I getting stuck conceptually.

make_fitting_function <- function(mod) {
   x <- xterms(mod)
   function(!! x) {
     predict(mod, newdata = list(!! x))
   }
}

Calling this function returns a function that can be called on separate vector arguments. For example:

f <- make_fitting_function(lm(mpg ~ wt, data = mtcars))
f(wt = c(1, 2, 3, 4, 5))

The result would be:

    1     2     3     4     5 
31.94 26.60 21.25 15.91 10.56 

However, this would also work for many more x variables (e.g.):

f <- make_fitting_function(lm(mpg ~ wt + am + carb, data = mtcars))
f(wt = c(1, 2, 3, 4, 5), am = rep(1, 5), carb = seq(2, 10, by = 2))

Ideally, this function should be able to be used by integrate in the case of a single variable.


Solution

  • You actually don't need to name the parameters; instead just make the data frame to pass in to predict using all of them.

    make_fitting_function <- function(model) {
        function(...) {
            predict(model, newdata=data.frame(...))
        }
    }
    f <- make_fitting_function(lm(mpg ~ wt + am + carb, data = mtcars))
    f(wt = c(1, 2, 3, 4, 5), am = rep(1, 5), carb = seq(2, 10, by = 2))
    ##         1         2         3         4         5 
    ## 30.589985 24.637415 18.684846 12.732277  6.779708