Change default arguments of an R function at runtime

后端 未结 4 2151
离开以前
离开以前 2021-02-19 22:59

Is it possible to change the default values of formal parameters in an R function at runtime?

Let\'s assume, we have the function

f <- function(x=1) {         


        
4条回答
  •  清酒与你
    2021-02-19 23:47

    I tried to do the same argument wrapping for the packagefinder library which has an alias of fp() pointing to findPackage(). I tried all sorts of methods, including using formals(), but in the end, the only thing that worked for me were the following 3 variations:

    #--------------------------------------
    # packagefinder
    #--------------------------------------
    # fp = findPackage
    # Set default to use: 
    #   fp(... , display = "console", return.df = TRUE)
    #--------------------------------------
    fp <- function(...) {
      packagefinder::fp(..., display="console", return.df=TRUE)
    }
    
    fp <- function(...) invisible(findPackage(..., display="console", return.df=TRUE))
    fp <- function(..., display="console", return.df=TRUE) packagefinder::fp(...,display=display, return.df=return.df)
    

    The formals() method I could not get to work.

    # Fail-1
    formals(fp) <- alist(... = , display="console", return.df=TRUE)
    
    # Fail-2
    MY_ARGS <- list(display="console", return.df=TRUE)
    formals(fp)[names(MY_ARGS)] <- MY_ARGS
    

    Other related posts on this:

    • R: Passing function arguments to override defaults of inner functions
    • Setting Function Defaults R on a Project Specific Basis
    • Change a function's default argument for all calls within a scope
    • https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/formals

提交回复
热议问题