R Functions

Introduction

In this chapter, you will learn about functions in R. Functions are reusable blocks of code that perform specific tasks. They help in organizing code, avoiding repetition, and making programs more modular and easier to maintain. Understanding how to create and use functions is essential for writing efficient and effective R programs.

Creating Functions

Basic Syntax

To define a function in R, you use the function keyword. The basic syntax for creating a function is as follows:

function_name <- function(arg1, arg2, ...) {
  # Code to execute
  return(value)
}
  • function_name: The name of the function.
  • arg1, arg2, ...: Arguments (inputs) to the function.
  • value: The value to return from the function.

Example 1: A Simple Function

This example defines a simple function that adds two numbers and returns the result.

Example:

# Define a function to add two numbers
add_numbers <- function(a, b) {
  sum <- a + b
  return(sum)
}

# Call the function with arguments 3 and 5
result <- add_numbers(3, 5)
print(result)  # Output: 8

Example 2: Function with Default Arguments

You can provide default values for function arguments. If no value is provided for an argument when the function is called, the default value is used.

Example:

# Define a function with default arguments
greet <- function(name = "World") {
  message <- paste("Hello,", name)
  return(message)
}

# Call the function without arguments
print(greet())  # Output: "Hello, World"

# Call the function with an argument
print(greet("Alice"))  # Output: "Hello, Alice"

Returning Values from Functions

Functions can return values using the return function. If no return statement is used, the value of the last expression is returned by default.

Example 3: Returning Multiple Values

In this example, the function returns a list containing multiple values.

Example:

# Define a function to return multiple values
stats <- function(x) {
  mean_val <- mean(x)
  sd_val <- sd(x)
  return(list(mean = mean_val, sd = sd_val))
}

# Call the function
data <- c(1, 2, 3, 4, 5)
result <- stats(data)
print(result)  # Output: $mean [1] 3, $sd [1] 1.581139

Example Programs with Functions

Example 4: Function to Calculate Factorial

This example defines a function to calculate the factorial of a number.

Example:

# Define a function to calculate factorial
factorial <- function(n) {
  if (n == 0) {
    return(1)
  } else {
    return(n * factorial(n - 1))
  }
}

# Call the function
print(factorial(5))  # Output: 120

Example 5: Function to Check Prime Numbers

This example defines a function to check if a number is prime.

Example:

# Define a function to check if a number is prime
is_prime <- function(n) {
  if (n <= 1) {
    return(FALSE)
  }
  for (i in 2:sqrt(n)) {
    if (n %% i == 0) {
      return(FALSE)
    }
  }
  return(TRUE)
}

# Call the function
print(is_prime(7))  # Output: TRUE
print(is_prime(8))  # Output: FALSE

Example 6: Function to Calculate Mean and Median

This example defines a function to calculate the mean and median of a numeric vector.

Example:

# Define a function to calculate mean and median
mean_median <- function(x) {
  mean_val <- mean(x)
  median_val <- median(x)
  return(list(mean = mean_val, median = median_val))
}

# Call the function
data <- c(1, 2, 3, 4, 5)
result <- mean_median(data)
print(result)  # Output: $mean [1] 3, $median [1] 3

Anonymous Functions

Anonymous functions are functions without a name. They are useful for short, temporary tasks and are often used as arguments to other functions.

Example 7: Using Anonymous Functions

Example:

# Use an anonymous function to square numbers in a vector
squared_numbers <- sapply(c(1, 2, 3, 4, 5), function(x) x^2)
print(squared_numbers)  # Output: 1 4 9 16 25

Conclusion

In this chapter, you learned about functions in R, including how to create functions, use default arguments, and return values from functions. You also saw examples of functions for various tasks, such as calculating factorials, checking prime numbers, and calculating statistics. Additionally, you learned about anonymous functions and their use cases. By mastering functions, you can write more modular, reusable, and efficient R code.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top