R Functions


R Functions

In this tutorial, we will learn about functions in R. We will cover the basics of creating, using, and understanding functions, including defining functions, passing arguments, and returning values.


What is a Function

A function in R is a block of code that performs a specific task. Functions help to break our program into smaller and modular chunks, making the code more organized and reusable.


Defining Functions

Functions in R are defined using the function keyword:

my_function <- function(arg1, arg2) {
  # function body
  result <- arg1 + arg2
  return(result)
}

The above code defines a function named my_function that takes two arguments and returns their sum.



Defining and Calling a Simple Function

In R, defining a function involves using the function keyword, and calling a function is done by writing the function name followed by parentheses containing any arguments.

For example,

  1. We start by defining a function named greet that takes one argument name.
  2. In the function body, we use the paste function to create a greeting message.
  3. The function returns the greeting message.
  4. We then call the function greet with a string argument and print the result.

R Program

greet <- function(name) {
  message <- paste('Hello,', name)
  return(message)
}
print(greet('Arjun'))

Output

[1] "Hello, Arjun"


Named Arguments in the Function Definition

In R, named arguments in function definitions allow you to specify default values, improving code readability and flexibility when calling the function.

For example,

  1. We define a function named multiply that takes two arguments a and b.
  2. Inside the function, we multiply a and b.
  3. The function returns the result of the multiplication.
  4. We call the function multiply with named arguments and print the result.

R Program

multiply <- function(a, b) {
  result <- a * b
  return(result)
}
print(multiply(a = 4, b = 5))

Output

[1] 20


Default Parameter Values

In R, default parameter values in function definitions let you set initial values for arguments, making them optional when calling the function.

For example,

  1. We define a function named power that takes two arguments base and exponent, with exponent having a default value of 2.
  2. Inside the function, we calculate the power using the ^ operator.
  3. The function returns the result of the power calculation.
  4. We call the function power with and without the second argument and print the results.

R Program

power <- function(base, exponent = 2) {
  result <- base ^ exponent
  return(result)
}
print(power(3))
print(power(3, 3))

Output

[1] 9
[1] 27


Return Value from Function

In R, the return value from a function is the last evaluated expression, or you can explicitly specify it using the return() function.

For example,

  1. We define a function named sum_values that takes two arguments x and y.
  2. Inside the function, we calculate the sum of x and y.
  3. The function returns the sum.
  4. We call the function sum_values with two numbers and print the result.

R Program

sum_values <- function(x, y) {
  return(x + y)
}
print(sum_values(10, 15))

Output

[1] 25


Nested Functions

In R, nested functions are functions defined within other functions, allowing for encapsulation and the creation of helper functions that are only accessible within the enclosing function.

For example,

  1. We define a function named outer_function that takes one argument outer_arg.
  2. Inside outer_function, we define another function named inner_function that takes one argument inner_arg.
  3. The inner_function returns the product of outer_arg and inner_arg.
  4. The outer_function calls inner_function with an argument and returns its result.
  5. We call the function outer_function with a number and print the result.

R Program

outer_function <- function(outer_arg) {
  inner_function <- function(inner_arg) {
    return(outer_arg * inner_arg)
  }
  return(inner_function(5))
}
print(outer_function(4))

Output

[1] 20


Function to Check if a Number is Even

  1. We define a function named is_even that takes one argument num.
  2. Inside the function, we use an if statement to check if the number is even.
  3. If the number is even, the function returns TRUE; otherwise, it returns FALSE.
  4. We call the function is_even with a few different numbers and print the results.

R Program

is_even <- function(num) {
  if (num %% 2 == 0) {
    return(TRUE)
  } else {
    return(FALSE)
  }
}
print(is_even(4))
print(is_even(7))

Output

[1] TRUE
[1] FALSE


Function to Check if a String Starts with a Specific Value

  1. We define a function named starts_with that takes two arguments: str and prefix.
  2. Inside the function, we use the substr function to extract the beginning part of the string.
  3. We then use an if statement to check if this extracted part matches the prefix.
  4. If the string starts with the prefix, the function returns TRUE; otherwise, it returns FALSE.
  5. We call the function starts_with with different strings and prefixes and print the results.

R Program

starts_with <- function(str, prefix) {
  if (substr(str, 1, nchar(prefix)) == prefix) {
    return(TRUE)
  } else {
    return(FALSE)
  }
}
print(starts_with('Hello, world!', 'Hello'))
print(starts_with('Hello, world!', 'world'))

Output

[1] TRUE
[1] FALSE


Function to Calculate the Factorial of a Number

  1. We define a function named factorial that takes one argument n.
  2. Inside the function, we use an if statement to check if n is 0 or 1, in which case the factorial is 1.
  3. If n is greater than 1, we recursively call the factorial function to compute the factorial.
  4. We call the function factorial with a few different numbers and print the results.

R Program

factorial <- function(n) {
  if (n == 0 || n == 1) {
    return(1)
  } else {
    return(n * factorial(n - 1))
  }
}
print(factorial(5))
print(factorial(0))

Output

[1] 120
[1] 1