Lesson 9 of 16

Defining Functions

Functions in R

Functions are created with the function keyword:

square <- function(x) {
  return(x ^ 2)
}

cat(square(5), "\n")  # 25

Implicit Return

In R, the last expression in a function is automatically returned. You can omit return():

square <- function(x) {
  x ^ 2
}

However, explicit return() is clearer, especially in functions with multiple branches.

Default Arguments

You can set default values for parameters:

greet <- function(name, greeting = "Hello") {
  cat(paste(greeting, name), "\n")
}

greet("Alice")            # Hello Alice
greet("Bob", "Hi")        # Hi Bob

Multiple Parameters

add <- function(a, b) {
  a + b
}

cat(add(3, 4), "\n")  # 7

Your Task

Write a function factorial that computes the factorial of a number using a loop (not recursion). Print factorial(0), factorial(5), and factorial(10).

R runtime loading...
Loading...
Click "Run" to execute your code.