Functions in R
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.
Example 1: 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,
- We start by defining a function named
greetthat takes one argumentname. - In the function body, we use the
pastefunction to create a greeting message. - The function returns the greeting message.
- We then call the function
greetwith 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"
Example 2: 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,
- We define a function named
multiplythat takes two argumentsaandb. - Inside the function, we multiply
aandb. - The function returns the result of the multiplication.
- We call the function
multiplywith 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
Example 3: 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,
- We define a function named
powerthat takes two argumentsbaseandexponent, withexponenthaving a default value of 2. - Inside the function, we calculate the power using the
^operator. - The function returns the result of the power calculation.
- We call the function
powerwith 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
Example 4: 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,
- We define a function named
sum_valuesthat takes two argumentsxandy. - Inside the function, we calculate the sum of
xandy. - The function returns the sum.
- We call the function
sum_valueswith two numbers and print the result.
R Program
sum_values <- function(x, y) {
return(x + y)
}
print(sum_values(10, 15))Output
[1] 25
Example 5: 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,
- We define a function named
outer_functionthat takes one argumentouter_arg. - Inside
outer_function, we define another function namedinner_functionthat takes one argumentinner_arg. - The
inner_functionreturns the product ofouter_argandinner_arg. - The
outer_functioncallsinner_functionwith an argument and returns its result. - We call the function
outer_functionwith 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
Example 6: Function to Check if a Number is Even
- We define a function named
is_eventhat takes one argumentnum. - Inside the function, we use an
ifstatement to check if the number is even. - If the number is even, the function returns
TRUE; otherwise, it returnsFALSE. - We call the function
is_evenwith 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
Example 7: Function to Check if a String Starts with a Specific Value
- We define a function named
starts_withthat takes two arguments:strandprefix. - Inside the function, we use the
substrfunction to extract the beginning part of the string. - We then use an
ifstatement to check if this extracted part matches theprefix. - If the string starts with the prefix, the function returns
TRUE; otherwise, it returnsFALSE. - We call the function
starts_withwith 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
Example 8: Function to Calculate the Factorial of a Number
- We define a function named
factorialthat takes one argumentn. - Inside the function, we use an
ifstatement to check ifnis 0 or 1, in which case the factorial is 1. - If
nis greater than 1, we recursively call thefactorialfunction to compute the factorial. - We call the function
factorialwith 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