R Methods and Functions

R Methods and Functions

Tutorial Name: Codes With Pankaj Website: www.codeswithpankaj.com


Table of Contents

  1. Introduction to Functions in R

  2. Creating Custom Functions

  3. Function Arguments

  4. Return Values

  5. Default Arguments in Functions

  6. Lazy Evaluation of Arguments

  7. Anonymous Functions

  8. Built-in Functions vs User-defined Functions

  9. Method Dispatch in R

    • S3 Methods

    • S4 Methods

    • Reference Classes (R5)


1. Introduction to Functions in R

Functions are a fundamental part of R programming, allowing you to encapsulate code into reusable blocks. A function in R is defined using the function() keyword and can take inputs (arguments) and return a result.

Example:

# Basic function structure
my_function <- function() {
  print("Hello, World!")
}

# Calling the function
my_function()

2. Creating Custom Functions

You can create custom functions in R to perform specific tasks. A function can take multiple arguments and return a value using the return() function.

Syntax:

function_name <- function(arg1, arg2, ...) {
  # Function body
  return(value)
}

Example:

# Function to calculate the sum of two numbers
sum_function <- function(a, b) {
  result <- a + b
  return(result)
}

# Calling the function
sum_result <- sum_function(5, 3)
print(sum_result)  # Output: 8

3. Function Arguments

Function arguments are the inputs that you provide to a function. R functions can accept multiple arguments, and you can pass these arguments by position or by name.

Example:

# Function with multiple arguments
multiply_function <- function(x, y) {
  return(x * y)
}

# Calling the function by position
print(multiply_function(2, 3))  # Output: 6

# Calling the function by name
print(multiply_function(y = 3, x = 2))  # Output: 6

4. Return Values

Functions in R return the last evaluated expression by default, even without an explicit return() statement. However, using return() can make your code more readable and clear.

Example:

# Function with return statement
subtract_function <- function(x, y) {
  return(x - y)
}

# Function without return statement
divide_function <- function(x, y) {
  x / y
}

print(subtract_function(10, 5))  # Output: 5
print(divide_function(10, 2))  # Output: 5

5. Default Arguments in Functions

You can set default values for function arguments, allowing the user to omit them when calling the function.

Example:

# Function with default arguments
power_function <- function(base, exponent = 2) {
  return(base ^ exponent)
}

# Calling the function with and without the default argument
print(power_function(3))  # Output: 9
print(power_function(3, 3))  # Output: 27

6. Lazy Evaluation of Arguments

R uses lazy evaluation, meaning that arguments to a function are only evaluated when they are actually used in the function body.

Example:

# Function demonstrating lazy evaluation
lazy_function <- function(x, y) {
  return(x^2)
}

# Only 'x' is evaluated
print(lazy_function(5, stop("Error!")))  # Output: 25

7. Anonymous Functions

Anonymous functions are functions that are defined without a name and are typically used for short, temporary tasks.

Example:

# Anonymous function used within sapply()
result <- sapply(1:5, function(x) x^2)
print(result)  # Output: 1 4 9 16 25

8. Built-in Functions vs User-defined Functions

R comes with a variety of built-in functions for tasks like data manipulation, statistical analysis, and more. However, you can create user-defined functions to address specific needs that aren't covered by the built-in functions.

Example:

# Built-in function
print(mean(c(1, 2, 3, 4, 5)))  # Output: 3

# User-defined function
custom_mean <- function(x) {
  return(sum(x) / length(x))
}

print(custom_mean(c(1, 2, 3, 4, 5)))  # Output: 3

9. Method Dispatch in R

R has three object-oriented programming systems: S3, S4, and Reference Classes (R5). These systems handle method dispatch, which is the process of deciding which method to call based on the object type.

9.1 S3 Methods

S3 is the simplest and most common object-oriented system in R. It uses a generic function that dispatches methods based on the class of the object.

Example:

# Define a generic function
print.my_class <- function(x) {
  cat("This is an object of class 'my_class':\n")
  print(x)
}

# Create an object of class 'my_class'
obj <- 1:5
class(obj) <- "my_class"

# Call the generic function
print(obj)

9.2 S4 Methods

S4 is a more formal and rigorous object-oriented system. It uses formal class definitions and method signatures.

Example:

# Define an S4 class
setClass("Person", slots = list(name = "character", age = "numeric"))

# Create an instance of the class
p <- new("Person", name = "John", age = 25)

# Define a method for the S4 class
setMethod("show", "Person", function(object) {
  cat(object@name, "is", object@age, "years old.\n")
})

# Call the method
show(p)

9.3 Reference Classes (R5)

Reference Classes (R5) are a more advanced system that supports mutable objects, similar to classes in other programming languages like Python or Java.

Example:

# Define an R5 class
Person <- setRefClass("Person",
  fields = list(name = "character", age = "numeric"),
  methods = list(
    greet = function() {
      cat("Hello, my name is", name, "\n")
    }
  )
)

# Create an instance of the class
john <- Person$new(name = "John", age = 30)

# Call a method on the instance
john$greet()  # Output: "Hello, my name is John"

Conclusion

Understanding functions and methods in R is crucial for writing efficient and reusable code. Whether you're working with built-in functions, creating your own custom functions, or exploring object-oriented programming with S3, S4, or R5 methods, mastering these concepts will enhance your R programming skills.

For more tutorials and resources, visit Codes With Pankaj at www.codeswithpankaj.com.

Last updated