In R, a function is a reusable block of code designed to perform a specific task. Functions help automate repetitive tasks, making code easier to manage and debug. R has many built-in functions, and users can also define their own.

Using Built-in Functions

R provides many pre-defined functions for common operations. Examples include:

# Using built-in functions
sum(1, 2, 3, 4, 5)  # Adds numbers
mean(c(2, 4, 6, 8, 10))  # Computes the average
round(3.14159, digits = 2)  # Rounds to 2 decimal places

Creating Your Own Functions

To create a function in R, use the function keyword. The basic syntax is:

function_name <- function(arguments) {
  # Code to execute
  return(result)  # Optional return statement
}

Example: A Simple Function

Here’s a function that adds two numbers:

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

# Using the function
result <- add_numbers(5, 10)
print(result)  # Output: 15

Function Arguments and Defaults

You can set default values for function arguments:

greet <- function(name = "Guest") {
  paste("Hello,", name, "!")
}

print(greet("Alice"))  # Output: "Hello, Alice!"
print(greet())  # Output: "Hello, Guest!"

Returning Values

A function can return values using return(), but if no explicit return statement is provided, R returns the last evaluated expression.

multiply <- function(x, y) {
  x * y  # Last evaluated expression is returned
}

print(multiply(3, 4))  # Output: 12

Conditional Statements in Functions

You can include conditional statements (if, else) inside functions.

check_number <- function(x) {
  if (x > 0) {
    return("Positive")
  } else if (x < 0) {
    return("Negative")
  } else {
    return("Zero")
  }
}

print(check_number(5))  # Output: "Positive"
print(check_number(-3)) # Output: "Negative"
print(check_number(0))  # Output: "Zero"

Loops in Functions

Loops (for, while) can be used inside functions.

sum_n_numbers <- function(n) {
  total <- 0
  for (i in 1:n) {
    total <- total + i
  }
  return(total)
}

print(sum_n_numbers(5))  # Output: 15 (1+2+3+4+5)

Applying Functions to Vectors

Functions can operate on vectors directly.

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

numbers <- c(1, 2, 3, 4, 5)
squared_numbers <- sapply(numbers, square)
print(squared_numbers)  # Output: 1 4 9 16 25

Anonymous Functions

Anonymous functions (without a name) are useful for short tasks.

result <- sapply(1:5, function(x) x^3)  # Cubes numbers from 1 to 5
print(result)  # Output: 1 8 27 64 125

Scope of Variables

Variables inside functions are local unless explicitly returned.

outer_var <- 10

modify_var <- function() {
  inner_var <- 5  # Local variable
  return(inner_var)
}

print(modify_var())  # Output: 5
print(outer_var)  # Output: 10 (unchanged)

Practical Example: Temperature Converter

Let’s create a function to convert Fahrenheit to Celsius.

fahrenheit_to_celsius <- function(f) {
  celsius <- (f - 32) * 5/9
  return(celsius)
}

print(fahrenheit_to_celsius(98.6))  # Output: 37