Unpacking argument lists for ellipsis in R

后端 未结 3 511
暗喜
暗喜 2020-12-08 04:09

I am confused by the use of the ellipsis (...) in some functions, i.e. how to pass an object containing the arguments as a single argument.

In Python it

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 04:36

    You can extract information from the ellipsis by calling list(...) inside the function. In this case, the info in the ellipsis is packaged as a list object. For example:

    > foo <- function(x,...){
    +   print(list(...))
    + }
    > foo(1:10,bar = 'bar','foobar')
    $bar
    [1] "bar"
    
    [[2]]
    [1] "foobar"
    

    You can achieve the desired behaviour from vectorised functions like file.path with a call to do.call, which is sometimes simpler to use with the wrapper splat (in the plyr package)

    > args <- c('baz', 'foob')
    > library(plyr)
    > splat(file.path)(c('/foo/bar', args))
    [1] "/foo/bar/baz/foob"
    

提交回复
热议问题