R Tutorial

Fundamentals of R

Variables

Input and Output

Decision Making

Control Flow

Functions

Strings

Vectors

Lists

Arrays

Matrices

Factors

DataFrames

Object Oriented Programming

Error Handling

File Handling

Packages in R

Data Interfaces

Data Visualization

Statistics

Machine Learning with R

Types of Functions in R

In R, functions are objects that can take in parameters and return a result. Functions are crucial in R as they help in organizing and abstracting code. R offers a variety of function types catering to various needs. This tutorial will give you an overview of the different types of functions in R.

1. Built-in Functions:

These are the standard functions that come with the R base package. You don't need to install or load any additional libraries to use them.

Examples:

  • Arithmetic functions: +, -, *, /
  • Statistical functions: mean(), sd(), var()
  • Sequence generation: seq(), rep()

2. User-defined Functions:

As the name suggests, these are the functions defined by the users to perform a specific task.

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

# Use the function
result <- add_numbers(5, 3)
print(result)  # Outputs: 8

3. Anonymous Functions:

Also known as lambda functions in some languages, these are functions without a name. They're typically used for short operations that you don't want to define a full function for.

# Using an anonymous function with the `sapply` function
result <- sapply(1:5, function(x) x^2)
print(result)  # Outputs: 1 4 9 16 25

4. Recursive Functions:

A recursive function is a function that calls itself.

# Function to compute factorial
factorial_recursive <- function(n) {
  if (n == 0) {
    return(1)
  } else {
    return(n * factorial_recursive(n-1))
  }
}

print(factorial_recursive(5))  # Outputs: 120

5. Nested Functions:

Functions defined inside another function are called nested functions.

outer_function <- function(a, b) {
  
  inner_function <- function(x) {
    return(x^2)
  }
  
  return(inner_function(a) + inner_function(b))
}

print(outer_function(3, 4))  # Outputs: 9 + 16 = 25

6. Primitive Functions:

These are basic, low-level functions written in C that are called from R. For example, functions like sum() are primitive functions. You typically won't write these yourself unless you're developing R or creating a low-level package.

7. Closure Functions:

Functions in R can capture environment data, making them closure functions. Any function that uses data not passed explicitly as an argument can be considered a closure.

make_multiplier <- function(multiplier) {
  function(x) {
    return(x * multiplier)
  }
}

double_it <- make_multiplier(2)
print(double_it(5))  # Outputs: 10

Conclusion:

Functions are fundamental to R programming. The versatility of function types in R allows for powerful and flexible programming, enabling you to build everything from simple scripts to complex data processing pipelines. Familiarizing yourself with the different types of functions and understanding when to use each is key to becoming proficient in R.

  1. User-Defined Functions in R:

    • Create custom functions for specific tasks.
    # Example: User-defined function
    my_function <- function(x, y) {
      result <- x + y
      return(result)
    }
    
  2. Statistical Functions in R:

    • R provides various statistical functions for descriptive and inferential analysis.
    # Example: Statistical functions
    mean_value <- mean(data_vector)
    
  3. Mathematical Functions in R:

    • Perform mathematical operations using built-in functions.
    # Example: Mathematical functions
    square_root <- sqrt(25)
    
  4. String Functions in R:

    • Manipulate and analyze strings with string functions.
    # Example: String functions
    string_length <- nchar("Hello, World!")
    
  5. Data Manipulation Functions in R:

    • Functions like subset and filter manipulate data.
    # Example: Data manipulation functions
    filtered_data <- subset(data_frame, condition)
    
  6. Plotting Functions in R:

    • Use functions like plot for data visualization.
    # Example: Plotting functions
    plot(x, y, type = "scatter")
    
  7. Time Series Functions in R:

    • Analyze and manipulate time series data using functions.
    # Example: Time series functions
    ts_object <- ts(data, frequency = 12)
    
  8. List Manipulation Functions in R:

    • Functions like lapply and unlist operate on lists.
    # Example: List manipulation functions
    modified_list <- lapply(my_list, function(x) x * 2)
    
  9. Function Types in R Base Package:

    • R has various function types, including mathematical, statistical, and data manipulation functions.
    # Example: Function types
    sample_mean <- mean(sample_data)
    
  10. Functional Programming in R:

    • Functional programming involves using functions as first-class citizens.
    # Example: Functional programming
    squared_values <- map(my_vector, ~ .x^2)
    
  11. Applying Functions to Data Frames in R:

    • Apply functions to data frames for row-wise or column-wise operations.
    # Example: Applying functions to data frames
    row_sums <- apply(data_frame, 1, sum)
    
  12. Vectorized Functions in R:

    • Vectorized functions operate on entire vectors efficiently.
    # Example: Vectorized functions
    multiplied_vector <- my_vector * 2
    
  13. R purrr Package for Advanced Function Operations:

    • The purrr package offers advanced functions for iteration and manipulation.
    # Example: Using purrr for advanced functions
    library(purrr)
    modified_list <- map(my_list, ~ .x * 2)