MODULE-3 R FUNCTIONS AND STATEMENTS
Function- A function is a set of statements organized together to perform a specific task. R
has a large number of in-built functions and the user can create their own functions.
In R, a function is an object so the R interpreter is able to pass control to the function, along
with arguments that may be necessary for the function to accomplish the actions.
The function in turn performs its task and returns control to the interpreter as well as any
result which may be stored in other objects.
Hello World Example
# R program to illustrate
# printing output of an R program
# print string
print("Hello World")
# print variable
x <- "Hello world example"
print(x)
Function Definition
An R function is created by using the keyword function. The basic syntax of an R function
definition is as follows −
function_name <- function(arg_1, arg_2, ...) {
Function body
}
Function Components
The different parts of a function are −
Function Name − This is the actual name of the function. It is stored in R
environment as an object with this name.
Arguments − An argument is a placeholder. When a function is invoked, you
pass a value to the argument. Arguments are optional; that is, a function may
contain no arguments. Also arguments can have default values.
Function Body − The function body contains a collection of statements that
defines what the function does.
Return Value − The return value of a function is the last expression in the
function body to be evaluated.
R has many in-built functions which can be directly called in the program without defining
them first. We can also create and use our own functions referred as user defined functions.
Built-in Function
Simple examples of in-built functions are seq(), mean(), max(), sum(x) and paste(...) etc.
They are directly called by user written programs. You can refer most widely used R
functions.
# Create a sequence of numbers from 32 to 44.
print(seq(32,44))
# Find mean of numbers from 25 to 82.
print(mean(25:82))
# Find sum of numbers from 41 to 68.
print(sum(41:68))
When we execute the above code, it produces the following result −
[1] 32 33 34 35 36 37 38 39 40 41 42 43 44
[1] 53.5
[1] 1526
User-defined Function
We can create user-defined functions in R. They are specific to what a user wants and once
created they can be used like the built-in functions. Below is an example of how a function is
created and used.
# Create a function to print squares of numbers in sequence.
new. Function <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
Calling a Function
# Create a function to print squares of numbers in sequence.
[Link] <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
# Call the function [Link] supplying 6 as an argument.
[Link](6)
When we execute the above code, it produces the following result −
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36
Calling a Function without an Argument
# Create a function without an argument.
[Link] <- function() {
for(i in 1:5) {
print(i^2)
}
}
# Call the function without supplying an argument.
[Link]()
When we execute the above code, it produces the following result −
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
Calling a Function with Argument Values (by position and by name)
The arguments to a function call can be supplied in the same sequence as defined in the
function or they can be supplied in a different sequence but assigned to the names of the
arguments.
# Create a function with arguments.
[Link] <- function(a,b,c) {
result <- a * b + c
print(result)
}
# Call the function by position of arguments.
[Link](5,3,11)
# Call the function by names of the arguments.
[Link](a = 11, b = 5, c = 3)
When we execute the above code, it produces the following result −
[1] 26
[1] 58
Calling a Function with Default Argument
We can define the value of the arguments in the function definition and call the function
without supplying any argument to get the default result. But we can also call such functions
by supplying new values of the argument and get non default result.
# Create a function with arguments.
[Link] <- function(a = 3, b = 6) {
result <- a * b
print(result)
}
# Call the function without giving any argument.
[Link]()
# Call the function with giving new values of the argument.
[Link](9,5)
When we execute the above code, it produces the following result −
[1] 18
[1] 45
Lazy Evaluation of Function
Arguments to functions are evaluated lazily, which means so they are evaluated only when
needed by the function body.
# Create a function with arguments.
[Link] <- function(a, b) {
print(a^2)
print(a)
print(b)
}
# Evaluate the function without supplying one of the arguments.
[Link](6)
When we execute the above code, it produces the following result −
[1] 36
[1] 6
Error in print(b) : argument "b" is missing, with no default
Control statements:
Control statements are expressions used to control the execution and flow of the program
based on the conditions provided in the statements. These structures are used to make a
decision after assessing the variable. In this article, we’ll discuss all the control statements
with the examples.
R provides various standard control structures for our requirements. The expr expression
consists of multiple statements that can be enclosed in braces {}.
It is more efficient to use built-in functions in R rather than control structures, whenever
possible. This facilitates the flow of execution to be controlled inside a function.
Control structures define the flow of the program. The decision is then made after the
variable is assessed
In R programming, there are 8 types of control statements as follows:
if condition
if-else condition
for loop
nested loops
while loop
repeat and break statement
return statement
next statement
if condition
1. if Condition in R
This task is carried out only if this condition is returned as TRUE. R makes it even easier:
You can drop the word then and specify your choice in an if statement. This control structure
checks the expression provided in parenthesis is true or not. If true, the execution of the
statements in braces {} continues
Syntax:
if (test_expression) {
statement
Example:
values <- 1:10
if (sample(values,1) <= 10)
print(paste(values, "is less than or equal to 10"))
.
Example:
x <- 100
if(x > 10){
print(paste(x, "is greater than 10"))
}
Output:
[1] "100 is greater than 10"
if-else condition
It is similar to if condition but when the test expression in if condition fails,
then statements in else condition are executed. 2. if-else Condition in R
An if…else statement contains the same elements as an if statement (see the preceding
section), with some extra elements:
The keyword else, placed after the first code block.
The second block of code, contained within braces, that has to be carried out,
only if the result of the condition in the if() statement is FALSE.
Syntax:
if (test_expression) {
statement
} else {
statement
Example:
val1 = 10 #Creating our first variable val1
val2 = 5 #Creating second variable val2
if (val1 > val2){ #Executing Conditional Statement based on the comparison
print("Value 1 is greater than Value 2")
} else if (val1 < val2){
print("Value 1 is less than Value 2")
}
for loop
It is a type of loop or sequence of statements executed repeatedly until exit
condition is reached.
A loop is a sequence of instructions that is repeated until a certain condition is reached. for,
while and repeat, with the additional clauses break and next are used to construct loops.
Syntax:
for(value in vector){
statements
....
....}
Example:
These control structures in R, made of the rectangular box ‘init’ and the diamond. It is
executed a known number of times. for is a block that is contained within curly braces.
values <- c(1,2,3,4,5)
for(id in 1:5){
print(values[id])
}
Example:
x <- letters[4:10]
for(i in x){
print(i)}
Output:
[1] "d"
[1] "e"
[1] "f"
[1] "g"
[1] "h"
[1] "i"
[1] "j"
Nested loops
Nested loops are similar to simple loops. Nested means loops inside loop. Moreover, nested
loops are used to manipulate the matrix.
It is similar to the standard for loop, which makes it easy to convert for loop to a foreach
loop. Unlike many parallel programming packages for R, foreach doesn’t require the body of
for loop to be turned into a function. We can call this a nesting operator because it is used to
create nested foreach loops.
Example:
mat <- matrix(1:10, 2)
for (id1 in seq(nrow(mat))) {
for (id2 in seq(ncol(mat))) {
print(mat[id1, id2])
Example:
# Defining matrix
m <- matrix(2:15, 2)
for (r in seq(nrow(m))) {
for (c in seq(ncol(m))) {
print(m[r, c])
}}
while loop
while loop is another kind of loop iterated until a condition is satisfied. The testing
expression is checked first before executing the body of loop.
Syntax:
while(expression){
statement
....
....
}
Example:
x=1
# Print 1 to 5
while(x <= 5){
print(x)
x=x+1
}
repeat loop and break statement
repeat is a loop which can be iterated many number of times but there is no exit condition
to come out from the loop. So, break statement is used to exit from the
loop. break statement can be used in any type of loop to exit from the loop.
Syntax:
repeat {
statements
....
....
if(expression) {
break
}}
Example:
x=1
# Print 1 to 5
repeat{
print(x)
x=x+1
if(x > 5){
break
}}
return statement
return statement is used to return the result of an executed function and returns control to
the calling function.
Syntax:
return(expression)
Example:
# Checks value is either positive, negative or zero
func <- function(x){
if(x > 0){
return("Positive")
}else if(x < 0){
return("Negative")
}else{
return("Zero")
#}Defining vector
}x <- 1:10
func(1)
# Print even numbers
func(0)
for(i in x){
func(-1)
if(i%%2 != 0){
Output:
[1] "Positive"
[1] "Zero"
[1] "Negative"
next statement
next statement is used to skip the current iteration without executing the further statements
and continues the next iteration cycle without terminating the loop.
next jumps to the next cycle without completing a particular iteration. In fact, it jumps to the
evaluation of the condition holding the current loop. Next statement enables to skip the
current iteration of a loop without terminating it.
Example:
x = 1: 4
for (i in x) {
if (i == 2) {
next
print(i)
Example:
next #Jumps to next loop
}
print(i)
}
Output:
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10
Switch Case Statement
Switch case statements are a substitute for long if statements that compare a variable to
several integral values. Switch case in R is a multiway branch statement. It allows a
variable to be tested for equality against a list of values.
Switch statement follows the approach of mapping and searching over a list of values. If
there is more than one match for a specific value, then the switch statement will return the
first match found of the value matched with the expression.
Syntax:
switch(expression, case1, case2, case3....)
Here, the expression is matched with the list of values and the corresponding value is
returned.
Important Points about Switch Case Statements:
An expression type with character string always matched to the listed cases.
An expression which is not a character string then this exp is coerced to integer.
For multiple matches, the first match element will be used.
No default argument case is available there in R switch case.
An unnamed case can be used, if there is no matched case.
Flowchart:
Example 1:
# Following is a simple R program
# to demonstrate syntax of switch.
val <- switch(
4,
"Geeks1",
"Geeks2",
"Geeks3",
"Geeks4",
"Geeks5",
"Geeks6"
)
print(val)
Output:
[1] "Geeks4"
Example 2:
# Following is val1 simple R program
# to demonstrate syntax of switch.
# Mathematical calculation
val1 = 6
val2 = 7
val3 = "s"
result = switch(
val3,
"a"= cat("Addition =", val1 + val2),
"d"= cat("Subtraction =", val1 - val2),
"r"= cat("Division = ", val1 / val2),
"s"= cat("Multiplication =", val1 * val2),
"m"= cat("Modulus =", val1 %% val2),
"p"= cat("Power =", val1 ^ val2)
)
print(result)
Output:
multiplication = 42NULL
5. while Loop in R
The format is while(cond) expr, where cond is the condition to test and expr is an
expression.
R would complain about the missing expression that was supposed to provide the required
True or False and in fact, it does not know ‘response’ before using it in the loop. We can also
do this because, if we answer right at first attempt, the loop will not be executed at all.
Example:
val = 2.987
while(val <= 4.987) {
val = val + 0.987
print(c(val,val-2,val-1))
}
6. repeat and break Statement in R
We use break statement inside a loop (repeat, for, while) to stop the iterations and flow the
control outside of the loop. While in a nested looping situation, where there is a loop inside
another loop, this statement exits from the innermost loop that is being evaluated.
A repeat loop is used to iterate over a block of code, multiple numbers of times. There is no
condition check in a repeat loop to exit the loop. We ourselves put a condition explicitly
inside the body of the loop and use the break statement to exit the loop. Failing to do so will
result in an infinite loop.
Syntax:
repeat {
# simulations; generate some value have an expectation if within some range,
# then exit the loop
if ((value - expectation) <= threshold) {
break
The repeat loop is an infinite loop and is used in association with a break statement.
Example:
Below, the code shows a repeat statement in R:
A break statement is used in a loop to stop the iterations and flow the control outside of the
loop.
Example of Repeat Statement in R:
val <- 5
repeat {
print(val)
val <- val+1
if (val == 10){
break
Example of Break Statement in R:
values = 1:10
for (id in values){
if (id == 2){
break
print(id)
}
7. return Statement in R
Many times, we will require some functions to do processing and return back the result. This
is accomplished with the return() statement in R.
Syntax:
return(expression)
Example:
check <- function(x) {
if (x > 0) {
result <- "Positive"
} else if (x < 0) {
result <- "Negative"
} else {
result <- "Zero"
return(result)
In the console window, we type:
> check(1)
> check(-10)
> check(0)
Compound Tests
The statement being tested with if , ifelse and switch can be any argument that results in a logical TRUE
or FALSE . This can be an equality check or even the result of is. numeric or [Link] . Sometimes we want
to test more than one relationship at a time
Wrapping up the Use of Loops in R
Be careful when you use the repeat statement.
Make sure that termination is explicitly set by testing a condition or we can end
up in an infinite loop.
It is better to use one or more function calls within the loop if a loop is getting
(too) big.