Functions: Built-In Functions in R
Functions: Built-In Functions in R
A function in R is an object containing multiple interrelated statements that are run together in a
predefined order every time the function is called. Functions in R can be built-in or created by
the user (user-defined). The main purpose of creating a user-defined function is to optimize our
program, avoid the repetition of the same block of code used for a specific task that is frequently
performed in a particular project, prevent us from inevitable and hard-to-debug errors related to
copy-paste operations, and make the code more readable.
Built-in Functions in R
There are plenty of helpful built-in functions in R used for various purposes. Some of the most
popular ones are:
min(), max(), mean(), median() – return the minimum / maximum / mean / median value
of a numeric vector, correspondingly
sum() – returns the sum of a numeric vector
range() – returns the minimum and maximum values of a numeric vector
abs() – returns the absulute value of a number
str() – shows the structure of an R object
print() – displays an R object on the console
ncol() – returns the number of columns of a matrix or a dataframe
length() – returns the number of items in an R object (a vector, a list, etc.)
nchar() – returns the number of characters in a character object
sort() – sorts a vector in ascending or descending (decreasing=TRUE) order
Example:
print(min(vector))
print(mean(vector))
print(median(vector))
print(sum(vector))
print(range(vector))
print(str(vector))
print(length(vector))
print(sort(vector, decreasing=TRUE))
print(exists('vector')) ## note the quotation marks
Creating a Function in R
While applying built-in functions facilitates many common tasks, often we need to create our
own function to automate the performance of a particular task. To declare a user-defined function
in R, we use the keyword function. The syntax is as follows:
Above, the main components of an R function are: function name, function parameters,
and function body. Let's take a look at each of them separately.
Example :-
my_function("Peter")
my_function("Lois")
my_function("Stewie")
Conditional Statements (if, if else, switch) in R
Conditional statements are a type of control statement that execute specific blocks of code
depending on the value of a condition.
1. IF--Else
The general structure is
if (condition) {
true_code_1
} else {
false_code_1
}
Example :
Example: Checking Even or Odd Numbers
x <- 3
if (x%%2 == 0) {
cat("x is an even number\n")
} else {
cat("x is an odd number\n")
}
#> x is an odd number
2 Using ifelse()
The ifelse() function allows you to select values based on whether a condition
is TRUE or FALSE:
x <- 9
if (x%%3 == 1) {
cat("The remainder of x divided by 3 is 1.\n")
} else if (x%%3 == 2) {
cat("The remainder of x divided by 3 is 2.\n")
} else {
cat("x is divisible by 3.\n")
}
#> x is divisible by 3.
4. Switch
The switch() function selects and returns a value based on an expression.
Syntax
Example:
x <- switch( 3, "first", "second", "third", "fourth" )
print(x)
day <- 3
weekday <- switch(day, "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
"Sunday")
print(weekday)
Repetitive execution: For and While loops
In R programming, we require a control structure to run a block of code multiple times.
There are three types of loops in R programming:
For Loop
While Loop
Repeat Loop
For Loop in R
A for-loop is one of the main control-flow constructs of the R programming language. It is used
to iterate over a collection of objects, such as a vector, a list, a matrix, or a dataframe, and apply
the same set of operations on each item of a given data structure.
Syntax :
Example
for (x in 1:10) {
print(x)
}
for (x in dice) {
print(x)
}
for (x in fruits) {
if (x == "banana") {
next
}
print(x)
}
2. While Loop
While loop in R programming language is used when the exact number of iterations of a loop is
not known beforehand. It executes the same code again and again until a stop condition is met.
While loop checks for the condition to be true or false n+1 times rather than n times. This is
because the while loop checks for the condition before entering the body of the loop.
while (test_expression) {
statement
update_expression
}
When the condition is tested and the result is false then the loop is terminated.
And when the tested result is True, then the loop will continue its execution.
Example :
result <- 1
i <- 1
# test expression
while (i < 6) {
print(result)
# update expression
i=i+1
result = result + 1
}
Assignment:
Write 2 programs to print 1 to 10 number except number 3 using for and while loop
Write a program to print first 20 even number using loop
3. Repeat
Repeat loop in R is used to iterate over a block of code multiple number of times. And also it
executes the same code again and again until a break statement is found.
Syntax :
repeat {
commands
if(condition) {
break
}
Example:
# update expression
i <- i + 1
# Breaking condition
if(i >5) {
break
}
}
Apply Functions in R
The R Apply Family is a set of functions in R that allow users to apply a function to elements of
a vector, list, or matrix.
The apply() functions form the basis of more complex combinations and helps to perform
operations with very few lines of code. More specifically, the family is made up of
the apply(), lapply() , sapply(), vapply(), mapply(), rapply(), and tapply() functions.
Use of apply depends on the structure of the data that you want to operate on and the format of
the output that you need.
1. Apply()
The apply() function lets us apply a function to the rows or columns of a matrix or data frame.
This function takes matrix or data frame as an argument along with function and whether it has
to be applied by row or column and returns the result in the form of a vector or array or list of
values obtained.
Syntax: