Loading...
Loading...

R Functions Tutorial

Functions are fundamental building blocks in R programming. Learn to create and use functions to write modular, reusable, and efficient R code.

1. Function Basics

Creating and using simple functions in R:

# Basic function structure
function_name <- function(arguments) {
  # Function body
  return(value)
}

# Example: Square a number
square <- function(x) {
  return(x * x)
}
square(5)  # Returns 25

# Function with default argument
greet <- function(name = "Guest") {
  paste("Hello,", name)
}
greet()       # Returns "Hello, Guest"
greet("Alice") # Returns "Hello, Alice"

Function Basics Quiz

What keyword is used to return a value from a function?

  • output
  • return
  • result

2. Function Arguments

Different ways to handle function parameters:

# Positional arguments
power <- function(x, exponent) {
  x^exponent
}
power(2, 3)  # 8

# Named arguments
power(exponent = 3, x = 2)  # 8

# Variable number of arguments
sum_all <- function(...) {
  sum(...)
}
sum_all(1, 2, 3, 4)  # 10

# Argument checking
safe_divide <- function(a, b) {
  if (b == 0) stop("Cannot divide by zero")
  a / b
}

Arguments Quiz

How do you specify a default argument value?

  • function(x = value)
  • function(x = value) (both are correct syntax)
  • function(x := value)

3. Return Values

Understanding function outputs in R:

# Explicit return
add <- function(a, b) {
  return(a + b)
}

# Implicit return (last expression)
multiply <- function(a, b) {
  a * b
}

# Returning multiple values
stats <- function(x) {
  list(mean = mean(x), sd = sd(x), length = length(x))
}

# Returning invisible values (for printing control)
quiet <- function(x) {
  invisible(x)
}

Return Values Quiz

What does R return if there's no explicit return statement?

  • NULL
  • The result of the last expression
  • An error

4. Advanced Function Concepts

Powerful function techniques in R:

# Anonymous functions (lambdas)
sapply(1:5, function(x) x^2)

# Function factories
power_factory <- function(exponent) {
  function(x) {
    x^exponent
  }
}
square <- power_factory(2)
cube <- power_factory(3)

# Recursive functions
factorial <- function(n) {
  if (n <= 1) return(1)
  n * factorial(n - 1)
}

# Closures
counter <- function() {
  count <- 0
  function() {
    count <<- count + 1
    count
  }
}

Advanced Functions Quiz

What is a function that creates other functions called?

  • Recursive function
  • Function factory
  • Lambda function

5. Function Best Practices

Writing clean, maintainable functions:

# Good practices:
# 1. Single responsibility principle
calculate_stats <- function(x) {
  c(mean = mean(x), median = median(x), sd = sd(x))
}

# 2. Meaningful names
calculate_bmi <- function(weight_kg, height_m) {
  weight_kg / (height_m^2)
}

# 3. Input validation
validate_percentage <- function(x) {
  stopifnot(is.numeric(x), x >= 0, x <= 100)
  # Function continues...
}

# 4. Document your functions
#' Calculate body mass index
#' 
#' @param weight_kg Weight in kilograms
#' @param height_m Height in meters
#' @return Numeric BMI value
calculate_bmi <- function(weight_kg, height_m) {
  weight_kg / (height_m^2)
}

Best Practices Quiz

What's the best approach for a function that does multiple unrelated tasks?

  • Keep it as one complex function
  • Split it into multiple single-purpose functions
  • Use comments to separate the tasks
0 Interaction
0 Views
Views
0 Likes
×
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

$ Allow cookies on this site ? (y/n)

top-home