match.call with default arguments

前端 未结 4 560
萌比男神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: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
    

提交回复
热议问题