Functions: Reusable Code Blocks
6 min read
R Course: Functions - Reusable Code Blocks 🧱
Hey there, future R guru! 👋 Welcome to our guide on functions. Ever felt like you're repeating the same lines of code over and over again? Well, functions are here to save the day! They are like your own custom-built tools that you can use whenever you need them.
Using Built-in Functions and the Help System (?) 🧰
Before we start building our own tools, let's look at the amazing toolbox R already provides.
The Problem: Imagine you have a list of numbers, and you need to find their sum, their average, and the largest number. You could write out the calculations manually, but what if the list has a thousand numbers? That would be a nightmare! 😱
The Solution: Built-in Functions
R comes with a ton of pre-written functions that perform common tasks. For our problem, we can use:
sum()to get the total.mean()to calculate the average.max()to find the maximum value.
# Our list of numbers
my_numbers <- c(10, 25, 5, 42, 18)
# Using built-in functions
total <- sum(my_numbers)
average <- mean(my_numbers)
biggest_number <- max(my_numbers)
# Let's see the results
print(total)
print(average)
print(biggest_number)Getting Help with ?
But how do you know what functions exist or what they do? 🤔 This is where the magical ? comes in. If you want to know more about a function, just put a question mark before its name.
?sum
?meanRunning this in your R console will open up the official documentation for that function, telling you what it does, what arguments it takes, and even showing you some examples. It's like having a super-helpful R expert sitting right next to you.
Fun Fact: The
c()function we used to create our list of numbers is one of the most fundamental functions in R. The 'c' stands for 'combine' or 'concatenate'. You'll be using it all the time!
Writing Your First Custom Function ✍️
Okay, the built-in functions are cool, but what if you need to do something specific that R doesn't have a ready-made function for? Time to create your own!
The Problem: Let's say you frequently need to calculate the area of a rectangle. You could write length * width every single time, but that's repetitive and prone to typos.
The Solution: A Custom Function
Let's build a function called calculate_rectangle_area.
Here’s the basic structure of a function in R:
function_name <- function(argument1, argument2) {
# Code to execute goes here
return(result)
}Now, let's apply this to our rectangle area problem:
# Defining our function
calculate_rectangle_area <- function(length, width) {
area <- length * width
return(area)
}
# Using our brand new function
area1 <- calculate_rectangle_area(10, 5)
area2 <- calculate_rectangle_area(20, 15)
# Let's see the results
print(area1)
print(area2)See how clean that is? Now, whenever you need to find the area of a rectangle, you just call your function. This makes your code more readable, easier to debug, and much more efficient.
Arguments, Default Values, and the Return Statement 📥📤
Let's dive a little deeper into how functions work.
Arguments
Arguments are the inputs you give to a function. In our calculate_rectangle_area function, length and width are the arguments. You can have as many arguments as you need.
Default Values
The Problem: What if you're designing a coffee machine function? Most people might want a regular-sized coffee. It would be tedious to specify "regular" every single time you call the function.
The Solution: Default Argument Values
You can set a default value for an argument. If you don't provide a value for that argument when you call the function, R will use the default one.
make_coffee <- function(type = "cappuccino", size = "regular") {
return(paste("Here is your", size, type))
}
# Calling the function with and without arguments
order1 <- make_coffee() # Will use both default values
order2 <- make_coffee("latte", "large") # We specify everything
print(order1)
print(order2)The return Statement
The return() statement is what a function gives back to you after it's done its job. It’s the result of the function's calculations.
In R, if you don't explicitly use return(), the function will automatically return the very last thing it calculated.
add_numbers <- function(a, b) {
a + b # No 'return()' here, but it still works!
}
result <- add_numbers(5, 3)
print(result) # This will print 8However, it's a very good industry practice to always use an explicit return() statement. It makes your code clearer and helps avoid unintentional results, especially in more complex functions.
Industry Practice: While R allows for implicit returns, explicitly stating
return()makes your function's intent clearer to others (and your future self!).
Understanding Variable Scope and Environments 🌍
This sounds a bit technical, but it's a fundamental concept that's pretty straightforward once you get the hang of it.
The Problem: Imagine you have a variable named my_variable outside your function and another variable with the same name inside your function. How does R know which one you're referring to?
The Solution: Variable Scope
Scope determines where a variable can be accessed.
- Global Scope: Variables defined outside of any function live in the global environment. You can access them from anywhere in your script, including inside functions.
- Local Scope: Variables created inside a function live in the local environment of that function. They are like temporary workers; they are created when the function is called and disappear once the function is finished. They cannot be accessed from outside the function.
Let's see this in action:
# A variable in the global environment
global_variable <- "I'm outside!"
my_function <- function() {
# A variable in the local environment
local_variable <- "I'm inside!"
print(local_variable)
print(global_variable) # We can access the global variable from here
}
my_function()
# Now, let's try to access the local variable from outside
# print(local_variable) # This will cause an error!Think of it like a company. The CEO (a global variable) is known to everyone in every department. However, an intern in the marketing department (a local variable) is only known within that department.
Environments in a Nutshell
An environment is essentially a container for a collection of objects (like variables and functions). When you start R, you are in the global environment. When you call a function, R creates a new, temporary environment for that function to do its work in. This is what keeps variables from different functions from interfering with each other.
Understanding scope helps you write more robust and bug-free code by preventing you from accidentally modifying variables you didn't intend to.
Additional Resources 📚
- R for Data Science - Functions Chapter: A fantastic and in-depth guide to functions in R. https://r4ds.had.co.nz/functions.html
- An Introduction to R - Writing your own functions: The official R documentation provides a solid overview. https://cran.r-project.org/doc/manuals/r-release/R-intro.html#Writing-your-own-functions
Challenge
Challenge: Create a Vector Statistics Calculator
Your task is to write a flexible R function that calculates summary statistics for a numeric vector. This will test your ability to define functions, handle arguments with default values, use built-in R functions, and control the function's output.
Requirements:
- Define a function named
calculate_stats. - The function must accept two arguments:
data_vector: A numeric vector containing the numbers to be analyzed.stat_type: A character string that specifies the desired output. This argument must have a default value of"summary".
- The function's logic should be as follows:
- If
stat_typeis"sum", it returns the sum of the vector. - If
stat_typeis"mean", it returns the mean of the vector. - If
stat_typeis"max", it returns the maximum value in the vector. - If
stat_typeis"summary"(the default), it must return a named numeric vector containing all three statistics: the sum, mean, and maximum. The names must be exactly"total","average", and"peak", in that order.
- If
- You must use the built-in R functions
sum(),mean(), andmax()to perform the calculations. - Use an explicit
return()statement to provide the output in all cases. - A global variable
SCRIPT_VERSIONis defined in the initial code. Your function must not modify this variable.
Expected result
Your script should define the calculate_stats function according to the instructions. When the provided initial code is run, the following variables should hold the correct results:
summary_output: A named numeric vector. Its structure should be:(Note: The exact formatting and number of decimal places in the printed output may vary, but the names and numeric values must be correct.)apachetotal average peak 394.000 56.286 120.000mean_output: A single numeric value equal to the mean ofsample_numbers(approximately 56.286).peak_output: A single numeric value equal to the maximum ofsample_numbers(120).- The global variable
SCRIPT_VERSIONmust remain unmodified and still hold the value"1.0.2".