match.call with default arguments

前端 未结 4 551
萌比男神i
萌比男神i 2020-12-14 18:32

As part of a function, I want to output a list of all the arguments and their values, including the default values. For example, a function with these arguments:

<         


        
相关标签:
4条回答
  • 2020-12-14 19:18

    Hopefully, this doesn't lead to dragons.

    foo <- function(x=NULL,y=NULL,z=2) {
      mget(names(formals()),sys.frame(sys.nframe()))
    
    }
    
    foo(x=4)
    
    $x
    [1] 4
    
    $y
    NULL
    
    $z
    [1] 2
    
    print(foo(x=4))
    
    $x
    [1] 4
    
    $y
    NULL
    
    $z
    [1] 2
    
    0 讨论(0)
  • 2020-12-14 19:26
     foo <- function(x=NULL,y=NULL,z=2) {
       X <- list(x,y,z); names(X) <- names(formals()); X
     }
     z <- foo(4)
     z
    #------
    $x
    [1] 4
    
    $y
    NULL
    
    $z
    [1] 4
    
    0 讨论(0)
  • 2020-12-14 19:31

    you can use a mix of the 2 , match.call and formals

    foo <- function(x=NULL,y=NULL,z=2)
    {
      ll <- as.list(match.call())[-1]     ## 
      myfor <- formals(foo)               ## formals with default arguments
      for ( v in names(myfor)){
                 if (!(v %in% names(ll)))
                    ll <- append(ll,myfor[v])  ## if arg is missing I add it
                 }
      ll
    }
    

    For example :

      foo(y=2)
    $y
    [1] 2
    
    $x
    NULL
    
    $z
    [1] 2
    
    > foo(y=2,x=1)
    $x
    [1] 1
    
    $y
    [1] 2
    
    $z
    [1] 2
    
    0 讨论(0)
  • 2020-12-14 19:31

    Here is an attempt to wrap this logic in a reusable function to drop in instead of match.call:

    match.call.defaults <- function(...) {
      call <- evalq(match.call(expand.dots = FALSE), parent.frame(1))
      formals <- evalq(formals(), parent.frame(1))
    
      for(i in setdiff(names(formals), names(call)))
        call[i] <- list( formals[[i]] )
    
    
      match.call(sys.function(sys.parent()), call)
    }
    

    It looks like it works:

    foo <- function(x=NULL,y=NULL,z=2,...) {
      match.call.defaults()
    }
    
    
    > foo(nugan='hand', x=4)
    foo(x = 4, y = NULL, z = 2, ... = pairlist(nugan = "hand"))
    
    0 讨论(0)
提交回复
热议问题