Next →

Output:


      

Plots:

Functions in R

Functions allow you to group code into reusable blocks. They help make your code cleaner and easier to maintain.

Creating a Function

Use the function() keyword to define a function.

greet <- function(name) {
  message <- paste("Hello,", name, "!")
  return(message)
}

print(greet("Alice"))

Using Arguments

Functions can take multiple arguments.

add_numbers <- function(a, b) {
  return(a + b)
}

print(add_numbers(5, 3))

Returning Values

A function can return a value using return(), or implicitly return the last evaluated expression.

add_numbers <- function(a, b) {
  return(a + b)
}

print(add_numbers(5, 3))

Functions make it easier to write modular, readable, and reusable R code.