Functions in R Programming


Introduction

Functions are a fundamental part of R programming that allow you to encapsulate reusable blocks of code. This tutorial covers creating custom functions, using default arguments, and understanding scope.

1. Writing Custom Functions

Custom functions in R are created using the function keyword.

Syntax:

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

Example:

    # Function to add two numbers
    add_numbers <- function(a, b) {
      result <- a + b
      return(result)
    }
    
    # Call the function
    add_numbers(5, 3)
        

2. Default Arguments

Default arguments allow you to specify default values for function parameters, which are used if no value is provided.

Example:

    # Function with default arguments
    greet <- function(name = "User") {
      message <- paste("Hello,", name)
      return(message)
    }
    
    # Call the function
    print(greet())          # Uses default value
    print(greet("Alice"))  # Uses provided value
        

3. Scope in R

Scope determines where a variable can be accessed. Variables defined inside a function are local to that function, while variables defined outside are global.

Example:

    # Global and local scope example
    x <- 10  # Global variable
    
    scope_example <- function() {
      x <- 20  # Local variable
      return(x)
    }
    
    print(x)                # Prints global x
    print(scope_example())  # Prints local x
    print(x)                # Global x remains unchanged
        

4. Returning Multiple Values

Functions in R can return multiple values using a list.

Example:

    # Function to return multiple values
    calculate <- function(a, b) {
      sum <- a + b
      product <- a * b
      return(list(sum = sum, product = product))
    }
    
    # Call the function
    result <- calculate(4, 5)
    print(result$sum)
    print(result$product)
        

5. Anonymous Functions

Anonymous functions are functions without a name, typically used for short operations.

Example:

    # Anonymous function
    squared <- (function(x) x^2)
    
    # Call the function
    print(squared(4))
        

Conclusion

Functions in R enable code reuse and better organization. By using custom functions, default arguments, and understanding scope, you can write more efficient and readable code.





Advertisement