Change default arguments of an R function at runtime

后端 未结 4 2152
离开以前
离开以前 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:38

    UPDATE: 2020-12-13

    This method is no longer available

    Yes, the Defaults package allows you to do this.

    0 讨论(0)
  • 2021-02-19 23:40

    An alternative (shown in a different SO post) is to use the formals function, e.g.:

    formals(f) <- 2

    0 讨论(0)
  • 2021-02-19 23:40

    As the Defaults package is no longer available from CRAN, you can use default.

    As an example:

    x <- list(a = 1, b = 2, c = 3)
    default::default(unlist) <- list(use.names = FALSE)
    unlist(x)
    #> [1] 1 2 3
    
    unlist <- default::reset_default(unlist)
    unlist(x)
    #> a b c 
    #> 1 2 3
    

    Created on 2019-03-22 by the reprex package (v0.2.0.9000).

    0 讨论(0)
  • 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
    0 讨论(0)
提交回复
热议问题