Control Structures and Functions
Control Structures and Functions
Conditional Statements :-
The if Statement
Example
a <- 33
b <- 200
if (b > a) {
print("b is greater than a")
}
If Else
The else keyword catches anything which isn't caught by the preceding
conditions:
Example
a <- 200
b <- 33
if (b > a) {
print("b is greater than a")
} else if (a == b) {
print("a and b are equal")
} else {
print("a is greater than b")
}
In this example, a is greater than b, so the first condition is not true, also
the else if condition is not true, so we go to the else condition and print to
screen that "a is greater than b".
R - Switch Statement
Syntax:
Here, the expression is matched with the list of values and the
corresponding value is returned.
Rules :-
o If expression type is a character string, the string is matched to the
listed cases.
o If there is more than one match, the first match element is used.
o No default case is available.
o If no case is matched, an unnamed case is used.
x <- switch(
3,
"first",
"second",
"third",
"fourth")
print(x)
When the above code is compiled and executed, it produces the following
result −
[1] "third"
Loops in R :-
Loops are handy because they save time, reduce errors, and they make
code more readable.
for loop
1 Like a while statement, except that it tests the condition at the end of the loop
body.
while loop
2 Repeats a statement or group of statements while a given condition is true. It
tests the condition before executing the loop body.
repeat loop
3 Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
next
4
The next statement simulates the behavior of R switch.
For Loop :-
Syntax :-
for (value in sequence) {
# block of code
numbers = c(1, 2, 3, 4, 5)
for (x in numbers) {
print(x)}
Output
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Example
for (x in 1:10) {
print(x)
}
With the for loop we can execute a set of statements, once for each item
in a vector, array, list, etc..
Example
Print every item in a list:
for (x in fruits) {
print(x)
}
Example
Print the number of dices:
for (x in dice) {
print(x)
}
R While Loops
Syntax :-
while (test_expression) {
# block of code
}
If the result is TRUE, then the block of code inside the while loop gets
executed.
[1] 55
Here, we have declared two variables: number and sum.
The test_condition inside the while statement is number <= 10.
This means that the while loop will continue to execute and calculate
the sum as long as the value of number is less than or equal to 10.
Example
i <- 1
while (i < 6) {
print(i)
i <- i + 1
}
In the example above, the loop will continue to produce numbers ranging
from 1 to 5. The loop will stop at 6 because 6 < 6 is FALSE.
R repeat Loop :-
repeat {
# statements
if(stop_condition) {
break
}
}
x=1
# Repeat loop
repeat {
print(x)
# Increment x by 1
x=x+1
}
Output
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Here, we have used a repeat loop to print numbers from 1 to 5. We have
used an if statement to provide a breaking condition which breaks the
loop if the value of x is greater than 4.
Example 2: Infinite repeat Loop
If you fail to put a break statement inside a repeat loop, it will lead to an
infinite loop. For example,
x=1
sum = 0
# Repeat loop
repeat {
# Calculate sum
sum = sum + x
# Print sum
print(sum)
# Increment x by 1
x=x+1
Output
[1] 1
[1] 3
[1] 6
[1] 10
.
.
.
In the above program, since we have not included any break statement
with an exit condition, the program prints the sum of numbers infinitely.
R next Statement
In R, the next statement skips the current iteration of the loop and starts
the loop from the next iteration.
if (test_condition) {
next
}
If the program encounters the next statement, any further execution of
code from the current iteration is skipped, and the next iteration begins.
Let's check out a program to print only even numbers from a vector of
numbers.
print(i)
}
Output
[1] 2
[1] 4
[1] 6
[1] 8
Here, we have used an if statement to check whether the current number
in the loop is odd or not.
If yes, the next statement inside the if block is executed, and the current
iteration is skipped.
Functions : -
R Functions
Introduction to R Functions
A function is just a block of code that you can call and run from any part
of your program. They are used to break our code in simple parts and
avoid repeatable codes.
You can pass data into functions with the help of parameters and return
some other data as a result. You can use the function() reserve keyword to
create a function in R.
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.
#mathamatical functions in R
print(sum(10:20))
print(min(10:20))
print(max(10:20))
print(avg(10:20))
print(abs(-78))
print(sqrt(25))
print(ceiling(45.7))
print(ceiling(45.2))
print(floor(45.9))
print(seq(10,20))
print(sin(60))
print(cos(60))
print(tan(60))
Output:
print(sqrt(25))
[1] 5
> print(ceiling(45.7))
[1] 46
> print(ceiling(45.2))
[1] 46
> print(floor(45.9))
[1] 45
> print(seq(10,20))
[1] 10 11 12 13 14 15 16 17 18 19 20
> print(sin(60))
[1] -0.3048106
> print(cos(60))
[1] -0.952413
> print(tan(60))
[1] 0.3200404
#String functions in R
s1="Hello"
print(print(s1))
s2='Hello'
print(print(s1))
a1=list(10,20,30,40)
print(length(s1))#calculate length of object
print(length(a1))#calculate length of object
print(nchar(s1))#display length of string
s3="Hello Students!"
print(substr(s3,7,14))
#Change Case
print(toupper(s3))
print(tolower(s3))
print(casefold(s3, upper = TRUE))
Output:
#String functions in R
> s1="Hello"
> print(print(s1))
[1] "Hello"
[1] "Hello"
> s2='Hello'
> print(print(s1))
[1] "Hello"
[1] "Hello"
> a1=list(10,20,30,40)
> print(length(s1))#calculate length of object
[1] 1
> print(length(a1))#calculate length of object
[1] 4
> print(nchar(s1))#display length of string
[1] 5
> s3="Hello Students!"
> print(substr(s3,7,14))
[1] "Students"
> #Change Case
> print(toupper(s3))
[1] "HELLO STUDENTS!"
> print(tolower(s3))
# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
new.function <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
# Call the function new.function supplying 6 as an argument.
new.function(6)
# Create a function without an argument.
new.function <- function() {
[1] "hello students!"
> print(casefold(s3, upper = TRUE))
[1] "HELLO STUDENTS!"
Creating a Function
Example
my_function <- function() { # create a function with the name
my_function
print("Hello World!")
}
Call a Function
Example
my_function <- function() {
print("Hello World!")
}
my_function("Peter")
my_function("Lois")
my_function("Stewie")
Output:-
[1] "Peter Griffin"
[1] "Lois Griffin"
[1] "Stewie Griffin"
Example 1
my_function("Peter", "Griffin")
[1] "Peter Griffin"
If you try to call the function with 1 or 3 arguments, you will get an
error:
Example
my_function("Peter")
Example 2
Example:
# Case 1:
print(Rectangle(2, 3))
# Case 2:
print(Rectangle(width = 8, length = 4))
# Case 3:
print(Rectangle())
Output
6
32
20