Lompati ke konten utama
eLearner.app
Modul 3 · Pelajaran 1 dari 25/10 dalam kursus~12 min
Pelajaran modul (1/2)

Fungsi Penulisan

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

Latihan#r.m3.l1.e1
Upaya: 0Memuat…

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

Memuat editor…
Tunjukkan petunjuk

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

Solusi tersedia setelah 3 upaya

Latihan#r.m3.l1.e2
Upaya: 0Memuat…

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

Memuat editor…
Tunjukkan petunjuk

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

Solusi tersedia setelah 3 upaya

Latihan#r.m3.l1.e3
Upaya: 0Memuat…

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.

Memuat editor…
Tunjukkan petunjuk

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

Solusi tersedia setelah 3 upaya

Latihan#r.m3.l1.e4
Upaya: 0Memuat…

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

Memuat editor…
Tunjukkan petunjuk

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

Solusi tersedia setelah 3 upaya

Latihan#r.m3.l1.e5
Upaya: 0Memuat…

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.

Memuat editor…
Tunjukkan petunjuk

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

Solusi tersedia setelah 3 upaya