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
greet
that takes one argumentname
. - In the function body, we use the
paste
function to create a greeting message. - The function returns the greeting message.
- 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"
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
multiply
that takes two argumentsa
andb
. - Inside the function, we multiply
a
andb
. - The function returns the result of the multiplication.
- 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
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
power
that takes two argumentsbase
andexponent
, withexponent
having 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
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
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_values
that takes two argumentsx
andy
. - Inside the function, we calculate the sum of
x
andy
. - The function returns the sum.
- 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
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_function
that takes one argumentouter_arg
. - Inside
outer_function
, we define another function namedinner_function
that takes one argumentinner_arg
. - The
inner_function
returns the product ofouter_arg
andinner_arg
. - The
outer_function
callsinner_function
with an argument and returns its result. - 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
Example 6: Function to Check if a Number is Even
- We define a function named
is_even
that takes one argumentnum
. - Inside the function, we use an
if
statement to check if the number is even. - If the number is even, the function returns
TRUE
; otherwise, it returnsFALSE
. - 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
Example 7: Function to Check if a String Starts with a Specific Value
- We define a function named
starts_with
that takes two arguments:str
andprefix
. - Inside the function, we use the
substr
function to extract the beginning part of the string. - We then use an
if
statement 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_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
Example 8: Function to Calculate the Factorial of a Number
- We define a function named
factorial
that takes one argumentn
. - Inside the function, we use an
if
statement to check ifn
is 0 or 1, in which case the factorial is 1. - If
n
is greater than 1, we recursively call thefactorial
function to compute the factorial. - 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