Define Custom Functions in R
In Python, we define a function using the def
reserved word followed by optional parameters in parenthesis. The body of the function is indented (very important!).
This defines the function but does not execute the body of the function.
In the below example, we define a new function called greet()
which will print Hello Dolly
when called.
1def greet():
2 print("Hello Dolly")
3
Once we have defined a function, we can call (or invoke) it as many times as we like.
greet()
Calling the function executes the function's body, in our case, it prints the text "Hello Dolly".
Hello Dolly
Function Arguments
Often a function will take its arguments, do some computation and return a value to be used as the value of the function call in the calling expression. The return keyword is used for this.
In the above example, we had a fixed output from the function ("Hello Dolly"). We can customize this using arguments. In the following revised code, we update the greeting based on the language specified at the time of calling the function:
1def greet(lang):
2 if lang == 'es':
3 return 'Hola'
4 elif lang == 'fr':
5 return 'Bonjour'
6 else:
7 return 'Hello'
8
There are a few important things to notice here:
- The function has one parameter
lang
. A parameter is a variable which we use in the function definition that is a "handle" that allows the code in the function to access the arguments for a particular function invocation. - We use the
if
condition to decide what the function should return depending on the argument supplied. If the argument passed ises
, then the function will returnHola
. If the argument isfr
, then the function will returnBonjour
and so on. - Notice that the function 'returns' a value not 'print' it, i.e., the value will be supplied back to the calling function and then the calling function can do whatever it wants with it.
Now that the function is defined, we can call it in the way we like:
1print(greet('es'),"Dolly")
2print(greet('fr'),"Dolly")
3print(greet('en'),"Dolly")
4
These calls will output the following:
1Hola Dolly
2Bonjour Dolly
3Hello Dolly
4
Multiple Arguments
A function can take multiple arguments. To do so, we define more than one parameter in the function definition. While calling the function, we simply add more arguments. The number and order of arguments and parameters must match. The following custom function calculates the area of a rectangle when its length and breadth are passed to it:
1def rectangle_area(l,b):
2 area = l*b
3 return area
4
We can then call the function along with print to output the results.
print(rectangle_area(5,4))
This will print '20'.
While writing programs, you will often think about whether to convert a part of your code into a function or not. There are a few guiding principles to help you decide whether to create a function or not to.
- Don't repeat yourself - make it work once and then reuse it
- If something gets too long or complex, break up logical chunks and put those chunks in functions
Exercises
- Make a function
reverse_string
that, given a string, returns that string in reverse. - Make a function that returns 'apples' if given a string, 'oranges' if given an integer, and 'bananas' if given anything else.