Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use R's ellipsis feature when writing your own function?
    text
    copied!<p>The R language has a nifty feature for defining functions that can take a variable number of arguments. For example, the function <code>data.frame</code> takes any number of arguments, and each argument becomes the data for a column in the resulting data table. Example usage:</p> <pre><code>&gt; data.frame(letters=c("a", "b", "c"), numbers=c(1,2,3), notes=c("do", "re", "mi")) letters numbers notes 1 a 1 do 2 b 2 re 3 c 3 mi </code></pre> <p>The function's signature includes an ellipsis, like this:</p> <pre><code>function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, stringsAsFactors = default.stringsAsFactors()) { [FUNCTION DEFINITION HERE] } </code></pre> <p>I would like to write a function that does something similar, taking multiple values and consolidating them into a single return value (as well as doing some other processing). In order to do this, I need to figure out how to "unpack" the <code>...</code> from the function's arguments within the function. I don't know how to do this. The relevant line in the function definition of <code>data.frame</code> is <code>object &lt;- as.list(substitute(list(...)))[-1L]</code>, which I can't make any sense of.</p> <p>So how can I convert the ellipsis from the function's signature into, for example, a list?</p> <p>To be more specific, how can I write <code>get_list_from_ellipsis</code> in the code below?</p> <pre><code>my_ellipsis_function(...) { input_list &lt;- get_list_from_ellipsis(...) output_list &lt;- lapply(X=input_list, FUN=do_something_interesting) return(output_list) } my_ellipsis_function(a=1:10,b=11:20,c=21:30) </code></pre> <hr> <h2>Edit</h2> <p>It seems there are two possible ways to do this. They are <code>as.list(substitute(list(...)))[-1L]</code> and <code>list(...)</code>. However, these two do not do exactly the same thing. (For differences, see examples in the answers.) Can anyone tell me what the practical difference between them is, and which one I should use?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload