6.3 Return a value from a function - Video Tutorials & Practice Problems
Video duration:
2m
Play a video:
<v Voiceover>Functions</v> provide a lot of utility and one of the most common reasons they're used is to return some sort of value. You feed in inputs, function operates on them somehow and returns a value. Returning this value is a key step in the function building process. So, let's take a look at a few of the ways we can do it. Let's build a function called double.num, whose purpose will be to double whatever input is provided. So you'll make it a function and the sole argument is x. (keyboard clicking) In here we'll write, x times two. By default, r will automatically return the last line of code. So, we don't need to specify what to return. Running this allows us to use it. Then, we can type in double.num, three, we type in double.num, five and it's returning two times the input. That's fantastic. Some people love that our returns the last line of a function, some people hate it. Fortunately, you can explicitly define what should be returned. So, we will once again create double.num, and notice each time we create a function, we overwrite the previous one, no problems. (keyboard clicking) Remember, this function has one input x, and we will say, return x times two. (keyboard clicking) Running this, will work much the same way. Double.num of three, gets six. Double.num of five gets 10. So, it's working as we please. Importantly, inside a function, anything that comes after a return statement, doesn't get executed. So, let's build a more complicated double.num that does a little bit more work and see what happens. So again, double.num gets a function, it's only argument is x. The very first line will be return x times two. Then, we'll have another line, the line that says, print, hello and a closing line that says, return 17. (keyboard clicking) We run this, and because the first line returns x times two, the following lines never even get executed. Recall the function, (keyboard clicking) return six is expected. Recall it with five, return 10 is expected. Functions can return an individual number, a string, a vector, a data frame, or a list, and that list can be arbitrarily complex. Any valid r object, can be returned by an r function, and learning how to harness this power, will greatly improve your coding capabilities.