Creating Functions in R
Functions in R are reusable blocks of code that perform specific tasks. They help organize code, reduce repetition, and improve readability. A function takes inputs (arguments), processes them, and returns an output. Functions are defined using the function()
keyword, followed by the function body enclosed in curly braces {}
.
Example: Creating a simple function to add two numbers.
add_numbers <- function(a, b) { return(a + b) } result <- add_numbers(3, 5) print(result) # Output: 8
Exercise: Write a function called multiply_numbers
that takes two arguments and returns their product.
Solution:
multiply_numbers <- function(x, y) { return(x * y) } result <- multiply_numbers(4, 6) print(result) # Output: 24
Function Syntax and Structure in R
The syntax of a function in R includes the function
keyword, parentheses ()
for arguments, and a body enclosed in curly braces {}
. The return()
statement specifies the output, but R automatically returns the last evaluated expression if no explicit return is provided.
Example: Function to calculate the area of a rectangle.
area_rectangle <- function(length, width) { area <- length * width return(area) } print(area_rectangle(4, 6)) # Output: 24
Exercise: Create a function named greet
that takes a name as an argument and returns a greeting message.
Solution:
greet <- function(name) { return(paste("Hello,", name, "!")) } print(greet("Alice")) # Output: "Hello, Alice!"
Working with Arguments and Return Values
Functions can have multiple arguments with optional default values. Arguments can be passed by position or name, making functions flexible. The return value is what the function produces as output.
Example: Function with multiple arguments and a return value.
calculate_bmi <- function(weight, height) { bmi <- weight / (height ^ 2) return(bmi) } bmi_result <- calculate_bmi(70, 1.75) print(bmi_result) # Output: 22.85714
Exercise: Write a function calculate_volume
that takes length, width, and height as arguments and returns the volume of a box.
Solution:
calculate_volume <- function(length, width, height) { volume <- length * width * height return(volume) } print(calculate_volume(3, 4, 5)) # Output: 60
Using Default Arguments Effectively
Default arguments allow you to specify predefined values for function parameters. If an argument isn't provided when calling the function, the default value is used instead.
Example: Function with a default argument.
apply_discount <- function(price, discount = 0.1) { discounted_price <- price * (1 - discount) return(discounted_price) } final_price <- apply_discount(100) print(final_price) # Output: 90
Exercise: Create a function power
that raises a number to a specified power, with a default power of 2.
Solution:
power <- function(base, exponent = 2) { return(base ^ exponent) } print(power(3)) # Output: 9 print(power(3, 3)) # Output: 27
Understanding Variable Scope in Functions
Variable scope determines where a variable is accessible. In R, variables defined inside a function are local (only accessible within that function), while variables defined outside are global (accessible anywhere).
Example: Demonstrating local and global variables.
global_var <- 10 my_function <- function() { local_var <- 5 print(global_var) # Accesses global variable print(local_var) # Accesses local variable } my_function() # Output: 10 # Output: 5
Exercise: Write a function update_counter
that increments a local counter variable by 1 each time it is called and prints the result.
Solution:
update_counter <- function() { counter <- 0 counter <- counter + 1 print(counter) } update_counter() # Output: 1 update_counter() # Output: 1