6.4 Gain flexibility with do.call - Video Tutorials & Practice Problems
Video duration:
3m
Play a video:
<v Voiceover>To increase</v> flexibility in calling functions r has a special function called do.call. This lets you specify a function name and then specify its arguments in a named list. We're gonna take a look at this by rebuilding our hello person function. So, hello.person gets function first, last equals doe, and dot dot dot as a catch all. Print, sprint f, hello percent s, percent s, first comma, last. We could call this as usual by doing hello.person, Jared, Lander, or we could use do.call. So, to use that you type in do.call, the first argument is the function, it could either be a character string or actually the function name itself. We will use a character string the first time around to see how it is. The second argument is args, has to be a named list, so you declare a list and you say, first equals Jared, last equals Lander. Run this and it's just like calling the function directly. Let's copy and paste this line and this time instead of putting hello.person in quotes let's just use the function name itself. Same exact result. It is a very handy way to call functions. It's true value becomes even more apparent when you allow a function to be pass another function as an argument. Let's take a look at this. Let's build a function whose first argument is a vector of numbers and second argument is some function you want to apply to those numbers. Let's clear the screen to make some room and we build this new function. It will be run.this. It takes on x, and func whose default value will be mean. The only line in this function will be do.call, we specify func, which is a user supplied function, and we say args equals list, x. Now, here you don't necessarily need a named list because why there are more than one arguments to mean it realizes which one is implied by the type and the position. We finish off this call and run this function. Now, if we just do run.this with one through ten, by default it will take the mean which is five point five. We could specify run.this on one through ten and specify mean as the function which gets us the same result. Otherwise we could do run.this, one through ten again, and say sum, add them all up, which give us 55 now. Or run.this, one through ten, sd for standard deviation, and we get the standard deviation. Using do.call adds a lot of flexibility in calling arguments. It is especially useful when the function name might be patched together by a bunch of different strings, for instance, you won't always use run, but sometimes it'll be run.this, run.that, run.nothing, and you can patch that function name together and then call it using do.call. This opens up a world of possibilities to greatly improve your programming flexibility.