Breaking the Ellipsis
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
I have often found instances where I want to pass a list to a function that accepts multiple items though an ellipsis. If you pass the list, the function considers that one item.
Lists are handy structures to use because they are not as judgmental as other structures. The ellipsis is also handy because it doesn’t ask you to figure out how many items you want to pass to a function. If I am writing a function with an ellipsis, I will check the class of the first item and determine if it is a list before processing the data.
This doesn’t obviously work if the function expects multiple list objects to be passed in. It also doesn’t work on functions you don’t write.
Here is an example problem I have run into many times:
As you can see, for loops and a blank starter column are not ideal. I could create a proxy for [cbind] to handle lists or separate parameters, but that is cumbersome and could cause problems if the underlying function changes.
The easy solution is to use the [do.call] function. [do.call] takes a function and a list (named if you want direct assignment to the function) and calls the passed function with each element of the list.
Here is another example I created to demonstrate how it works:
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.