Keeping function names when stored in an object

后端 未结 2 776
后悔当初
后悔当初 2021-01-15 15:03

I am preparing a package where users have to store functions and their associated arguments in a list for later use. This is a typical example of how it works:<

相关标签:
2条回答
  • 2021-01-15 15:42

    You could use alists:

    parameters <- list(a1 = alist(fun = dnorm,
                                 args = list(mean = 150, sd = 100)),
                       a2 = alist(fun = dpois,
                                 args = list(lambda = 40)))
    #probably better to write a constructor method for parameters objects
    
    
    x <- 1:100
    myfunction <- function(x, var, parameters)
    { f <- function(x) do.call(fun, c(list(x), args))
      formals(f) <- c(formals(f), parameters[[var]]) 
      results <- list(var = var,
                      y = f(x),
                      parameters = parameters)
      class(results) <- "customclass"
      return(results)
    }
    
    print.customclass <- function(X)
    {
      cat("Function name:", X$parameters[[X$var]]$fun)
    }
    
    myfunction(x, "a1", parameters)
    #Function name: dnorm
    
    0 讨论(0)
  • 2021-01-15 15:45

    I'd suggest to define your parameters argument with the function name, instead of the function itself and retrieve the function in the body of myfunction through match.fun:

        parameters <- list(a1 = list(fun = "dnorm",
                             args = list(mean = 150, sd = 100)),
                   a2 = list(fun = "dpois",
                             args = list(lambda = 40)))
    
        myfunction <- function(x, var, parameters)
        {
            results <- list(var = var,
                    y = do.call(match.fun(parameters[[var]]$fun), 
                                c(list(x), parameters[[var]]$args)),
                    parameters = parameters)
            class(results) <- "customclass"
            return(results)
        }
    
    0 讨论(0)
提交回复
热议问题