Перейти к основному содержимому
eLearner.app
Модуль 3 · Урок 1 из 25/10 в курсе~12 min
Уроки модуля (1/2)

Написание функций

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

Упражнение#r.m3.l1.e1
Попыток: 0Загрузка…

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

Загрузка редактора…
Показать подсказку

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

Решение доступно после 3 попыток

Упражнение#r.m3.l1.e2
Попыток: 0Загрузка…

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

Загрузка редактора…
Показать подсказку

Define the function with parameters width and height, and return width * height.

Решение доступно после 3 попыток

Упражнение#r.m3.l1.e3
Попыток: 0Загрузка…

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.

Загрузка редактора…
Показать подсказку

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

Решение доступно после 3 попыток

Упражнение#r.m3.l1.e4
Попыток: 0Загрузка…

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)).

Загрузка редактора…
Показать подсказку

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

Решение доступно после 3 попыток

Упражнение#r.m3.l1.e5
Попыток: 0Загрузка…

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.

Загрузка редактора…
Показать подсказку

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

Решение доступно после 3 попыток