メインコンテンツにスキップ
eLearner.app
モジュール 3 · レッスン 1 / 2コース内の 5/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 回の試行後に解決策が利用可能になります