Skip to main content
eLearner.app
Module 3 · Lesson 1 of 25/10 in the course~12 min
Module lessons (1/2)

Writing Functions

In R, functions are first-class citizens (objects in their own right) and allow you to structure your code into modular, reusable, and well-organized blocks.

Defining a Function

To define a function, use the function keyword and assign the created object to a variable (the function name) using the assignment operator <-:

Code
# Simple function definition
greet_user <- function() {
  print("Hello, User!")
}

# Invoking the function
greet_user()

Parameters and Return Values

Functions can accept one or more parameters. To explicitly return a value, use the return() function. If return() is omitted, R will automatically return the value of the last evaluated expression in the function body.

Code
# Function that adds two numbers and returns the result
add_numbers <- function(a, b) {
  sum_result <- a + b
  return(sum_result)
}

total <- add_numbers(5, 7)
print(total) # Prints 12

Default Arguments

You can specify default values for a function's parameters. If the argument is not provided when the function is invoked, R will use the default value:

Code
# The function uses a default discount rate of 10% (0.10)
apply_discount <- function(price, discount = 0.10) {
  discounted_price <- price * (1 - discount)
  return(discounted_price)
}

# Uses the default (10%)
print(apply_discount(100)) # Prints 90

# Specifies a custom discount (20%)
print(apply_discount(100, 0.20)) # Prints 80

Returning Multiple Values with Lists

Since a function in R can only return a single object directly via return(), if we need to return multiple values (possibly of different types or lengths), we can bundle them inside a list (list):

Code
get_stats <- function(v) {
  stats <- list(
    mean_val = mean(v),
    max_val = max(v)
  )
  return(stats)
}

results <- get_stats(c(10, 20, 30))
print(results$mean_val) # Prints 20

Anonymous Functions and sapply

Anonymous functions (functions without a name defined inline) are extremely useful when paired with functions like sapply() to apply quick transformations on elements of a vector or list.

In modern R (from version 4.1.0 onwards), you can define anonymous functions using the shorthand syntax \(x) in addition to the classic function(x):

Code
v <- c(1, 2, 3)

# Using sapply with a classic anonymous function
sapply(v, function(x) x^2) # 1 4 9

# Using sapply with shorthand syntax (R >= 4.1.0)
sapply(v, \(x) x^2) # 1 4 9

Try it yourself

Exercise#r.m3.l1.e1
Attempts: 0Loading…

Define a function named double_value that accepts a single argument x and returns its double (x * 2) using return().

Loading editor…
Show hint

Usa la sintassi: double_value <- function(x) { return(x * 2) }

Solution available after 3 attempts

Exercise#r.m3.l1.e2
Attempts: 0Loading…

Define a function named calculate_area that accepts two arguments: width and height. The function must return their product using return().

Loading editor…
Show hint

Definisci la funzione con parametri width e height, e restituisci width * height.

Solution available after 3 attempts

Exercise#r.m3.l1.e3
Attempts: 0Loading…

Define a function named calculate_tax that accepts a required argument amount and an optional argument rate with a default value of 0.22. Return the product amount * rate.

Loading editor…
Show hint

Usa: calculate_tax <- function(amount, rate = 0.22) { return(amount * rate) }

Solution available after 3 attempts

Exercise#r.m3.l1.e4
Attempts: 0Loading…

Define a function named analyze_vector that accepts a vector v. The function must return a list containing two elements named sum (the sum of the vector, calculated with sum(v)) and len (the length of the vector, calculated with length(v)).

Loading editor…
Show hint

Use the syntax: analyze_vector <- function(v) { return(list(sum = sum(v), len = length(v))) }

Solution available after 3 attempts

Exercise#r.m3.l1.e5
Attempts: 0Loading…

Given the vector v, use the sapply() function with an anonymous function to triple the value of each element (multiplying it by 3). Save the result in the variable tripled.

Loading editor…
Show hint

Use: tripled <- sapply(v, function(x) x * 3)

Solution available after 3 attempts