Learning Goals
- Learn to write your own functions
Functions
Functions in programming are reusable blocks of code designed to perform specific tasks. They take inputs (arguments), process them, and return outputs, helping to simplify, organise, and streamline your code. Generally, you should consider writing a function when you find yourself copying and pasting a block of code repeatedly.
In R, the syntax to write your own function follows this structure:
To write a function, you need to typically list three key variables. First, you need to specify the name for your function. Second, you need to list the inputs required for the function to evaluate. These inputs are termed arguments. Third, you specified the body of the function, which refers to the block of code for the function to perform its intended task. The body is typically enclosed in curly parentheses.
Below is a simple example of writing a function that sums up the values of two arguments. The return()
function was employed to specify the value returned by the written function.
Run the code below to apply the written function above. Try changing the values in the arguments.
Ellipsis (…)
If you have tried including more than two arguments in the function above, you would receive an error message because the function was specified to expect only two arguments. You could command R to take on an arbitrary number of arguments by using a special ellipsis argument ...
(dot-dot-dot). This allows the function to take any number of named or unnamed arguments.
Try inputting any number of numerical values as arguments into the function below and run the code.
Exercise 4.1
Create a simple function named greet
that takes a name as input and returns a greeting message like below:
#greet("Alice")
#Output: "Hello, Alice!"
greet <- function(x){
paste0("Hello, ", x, "!")
}
Exercise 4.2
Let’s try to create our own Cohen’s d effect size calculator for t-tests similar to one that can be found online.
Bazinga!
We may also incorporate conditional statements into our functions. Here’s an example of creating a function named Bazinga
that checks whether a number is a prime number.
Fun Fact
“Bazinga” is a catchphrase used by Dr Sheldon Cooper of The Big Bang Theory, who is a fan of prime numbers!