Can I remove an element in … (dot-dot-dot) and pass it on?

后端 未结 5 1819
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 16:01

Is it possible to remove an element from ... and pass ... onto other functions? My first two attempts failed:

parent = function(...)
{

   a = list(...)
            


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-09 16:08

    Your child function is erroneous. Try

    > child(a=1)
    Error in str(a) : object 'a' not found
    

    edit : no longer applicable.

    The ... argument should only be used to pass parameters to a next function. You cannot get the parameters from there that easily, unless you convert them to a list. So your child function could be :

    child <- function(...)
    {
      mc <- match.call()  # or mc <- list(...)
      str(mc$a)
    }
    

    Which doesn't make sense. You can't know whether the user specified a or not. The correct way would be to include a as an argument in your function. the ... is to pass arguments to the next one :

    child <- function(a, ...){
        str(a,...)
    }
    

    Then you could do :

    parent <- function(...){
    
       mc <- match.call()
       mc$toRemove <- NULL
       mc[[1L]] <- as.name("child")
       eval(mc)
    
    }
    

    or use the list(...) and do.call() construct @Gavin proposed. The benefit of match.call() is that you can include non-dot arguments as well. This allows your parent function to specify defaults for the child :

    parent <- function(a=3, ...){
        ... (see above)
    }
    

提交回复
热议问题