How to use R's ellipsis feature when writing your own function?

前端 未结 5 470
星月不相逢
星月不相逢 2020-11-22 03:43

The R language has a nifty feature for defining functions that can take a variable number of arguments. For example, the function data.frame takes any number of

5条回答
  •  被撕碎了的回忆
    2020-11-22 04:19

    You can convert the ellipsis into a list with list(), and then perform your operations on it:

    > test.func <- function(...) { lapply(list(...), class) }
    > test.func(a="b", b=1)
    $a
    [1] "character"
    
    $b
    [1] "numeric"
    

    So your get_list_from_ellipsis function is nothing more than list.

    A valid use case for this is in cases where you want to pass in an unknown number of objects for operation (as in your example of c() or data.frame()). It's not a good idea to use the ... when you know each parameter in advance, however, as it adds some ambiguity and further complication to the argument string (and makes the function signature unclear to any other user). The argument list is an important piece of documentation for function users.

    Otherwise, it is also useful for cases when you want to pass through parameters to a subfunction without exposing them all in your own function arguments. This can be noted in the function documentation.

提交回复
热议问题