R Tutorial



R FUNCTIONS


Functions in R

Functions are blocks of reusable code designed to perform a specific task. They help organize your code, make it modular, and easier to maintain.

Why Use Functions?

  • Avoid repeating code (reusability).
  • Break complex problems into smaller parts.
  • Improve readability and structure.
  • Easy to test and debug.

Creating Functions in R

The basic syntax for creating a function is:

function_name <- function(arg1, arg2, ...) {
  # Code to execute
  result <- arg1 + arg2  # example operation
  return(result)        # return the output
}
  

- function_name is the name you assign to your function.
- Inside the parentheses are arguments (inputs) your function accepts.
- The function body contains code that processes inputs.
- The return() statement outputs the final value.

Example 1: Simple Addition Function

add_numbers <- function(a, b) {
  sum <- a + b
  return(sum)
}

result <- add_numbers(5, 3)
print(result)  # Output: 8
  

Example 2: Function Without Return

If you omit the return() statement, R returns the value of the last expression:

multiply <- function(x, y) {
  x * y
}

print(multiply(4, 6))  # Output: 24
  

Example 3: Function with Default Arguments

You can assign default values to arguments. If no value is passed, the default is used:

power <- function(base, exponent = 2) {
  base ^ exponent
}

print(power(5))      # Output: 25 (5^2)
print(power(5, 3))   # Output: 125 (5^3)
  

Example 4: Function with Multiple Statements

circle_area <- function(radius) {
  area <- pi * radius^2
  cat("The area of the circle is:", area, "\n")
  return(area)
}

result <- circle_area(3)  # Prints message and returns area
  

Calling Functions

To use a function, write its name followed by parentheses with any required arguments inside:

function_name(argument1, argument2, ...)
  

Summary

  • Functions help organize and reuse code.
  • Defined using function() with arguments inside parentheses.
  • Use return() to send back output (optional).
  • Arguments can have default values.
  • Functions can contain multiple lines and complex logic.

Practice Exercises

  • Create a function that calculates the factorial of a number.
  • Write a function to check if a number is even or odd.
  • Define a function that converts Celsius to Fahrenheit.
  • Write a function that returns the larger of two numbers.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review