Split up `…` arguments and distribute to multiple functions

后端 未结 3 1349
温柔的废话
温柔的废话 2020-11-27 05:22

Using the following function foo() as a simple example, I\'d like to distribute the values given in ... two different functions, if possible.

3条回答
  •  粉色の甜心
    2020-11-27 06:03

    1. Why does grep error before sum?

      See that sum is a lot more accommodating with its arguments:

      X <- c(1:5, NA, 6:10)
      sum(X, na.rm = TRUE, value = TRUE)
      ## [1] 56
      

      It doesn't failed because it doesn't care about other named arguments, so the value = TRUE simplifies to just TRUE which sums to 1. Incidentally:

      sum(X, na.rm = TRUE)
      ## [1] 55
      
    2. How to split ... to different functions?

      One method (that is very prone to error) is to look for the args for the target functions. For instance:

      foo <- function(x, y, ...){
          argnames <- names(list(...))
          sumargs <- intersect(argnames, names(as.list(args(sum))))
          grepargs <- intersect(argnames, names(as.list(args(grep))))
          list(sum = do.call(sum, c(list(x), list(...)[sumargs])),
               grep = do.call(grep, c(list("abc", y), list(...)[grepargs])))
      }
      

      This is prone to error anytime the arguments a function uses are not properly reported by args, such as S3 objects. As an example:

      names(as.list(args(plot)))
      ## [1] "x"   "y"   "..." ""   
      names(as.list(args(plot.default)))
      ##  [1] "x"           "y"           "type"        "xlim"        "ylim"       
      ##  [6] "log"         "main"        "sub"         "xlab"        "ylab"       
      ## [11] "ann"         "axes"        "frame.plot"  "panel.first" "panel.last" 
      ## [16] "asp"         "..."         ""           
      

      In this case, you could substitute the appropriate S3 function. Because of this, I don't have a generalized solution for this (though I don't know that it does or does not exist).

提交回复
热议问题