0% found this document useful (0 votes)
16 views

Control Structures and Functions

The document discusses control structures and functions in R programming language. It covers conditional statements like if-else and switch statements as well as loops like for, while, repeat and next. It also explains different types of functions in R including built-in functions and user defined functions.

Uploaded by

tapstaps902
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Control Structures and Functions

The document discusses control structures and functions in R programming language. It covers conditional statements like if-else and switch statements as well as loops like for, while, repeat and next. It also explains different types of functions in R including built-in functions and user defined functions.

Uploaded by

tapstaps902
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 20

Control Structures and Functions :-

Conditional Statements :-
The if Statement

An "if statement" is written with the if keyword, and it is used to specify


a block of code to be executed if a condition is TRUE:

Example

a <- 33
b <- 200

if (b > a) {
print("b is greater than a")
}

IMP :- R uses curly brackets { } to define the scope in the code.

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:

switch(expression, case1, case2, case3....)

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 can execute a block of code as long as a specified condition is


reached.

Loops are handy because they save time, reduce errors, and they make
code more readable.

R has two loop commands:


 while loops
 for loops

R programming language provides the following kinds of loop to handle


looping requirements. Click the following links to check their detail.
Sr.No. Loop Type & Description

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

Here, sequence is an object of elements and value takes in each of those


elements. In each iteration, the block of code is executed. For example,

numbers = c(1, 2, 3, 4, 5)

# for loop to print all elements in numbers

for (x in numbers) {

print(x)}

Output

[1] 1

[1] 2

[1] 3

[1] 4

[1] 5

In this program, we have used a for loop to iterate through a sequence of


numbers called numbers. In each iteration, the variable x stores the
element from the sequence and the block of code is executed.
A for loop is used for iterating over a sequence:

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:

fruits <- list("apple", "banana", "cherry")

for (x in fruits) {
print(x)
}

Example
Print the number of dices:

dice <- c(1, 2, 3, 4, 5, 6)

for (x in dice) {
print(x)
}
R While Loops
Syntax :-
while (test_expression) {
# block of code
}

 Here, the test_expression is first evaluated.

 If the result is TRUE, then the block of code inside the while loop gets
executed.

 Once the execution is completed, the test_expression is evaluated again


and the same process is repeated until the test_expression evaluates
to FALSE.

 The while loop will terminate when the boolean expression


returns FALSE.
Example 1: R while Loop
# variable to store current number
number = 1
# variable to store current sum
sum = 0
# while loop to calculate sum
while(number <= 10) {
# calculate sum
sum = sum + number
# increment number by 1
number = number + 1}
print(sum)
Output

[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.

With the while loop we can execute a set of statements as long as a


condition is TRUE:

Example

Print i as long as i is less than 6:

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.

The while loop requires relevant variables to be ready, in this example we


need to define an indexing variable, i, which we set to 1.

R repeat Loop :-

We use the R repeat loop to execute a code block multiple times.


However, the repeat loop doesn't have any condition to terminate the
lYou can use the repeat loop in R to execute a block of code multiple
times. However, the repeat loop does not have any condition to terminate
the loop. You need to put an exit condition implicitly with a break
statement inside the loop.
The syntax of repeat loop is:

repeat {
# statements
if(stop_condition) {
break
}
}

Here, we have used the repeat keyword to create a repeat loop. It is


different from the for and while loop because it does not use a predefined
condition to exit from the loop.

Example 1: R repeat Loop


Let's see an example that will print numbers using a repeat loop and will
execute until the break statement is executed.

x=1

# Repeat loop
repeat {

print(x)

# Break statement to terminate if x > 4


if (x > 4) {
break
}

# 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.

The syntax of the next statement is:

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.

# vector to be iterated over


x = c(1, 2, 3, 4, 5, 6, 7, 8)

# for loop with next statement


for(i in x) {

# if condition with next


if(i %% 2 != 0) {
next
}

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.

The syntax is:

func_name <- function (parameters)


{
statement
}

Here, func_name is the name of the function. For example,

# define a function to compute power


power <- function(a, b) {
print(paste("a raised to the power b is: ", a^b))
}
Here, we have defined a function called power which takes two
parameters - a and b. Inside the function, we have included a code to print
the value of a raised to the power b.

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.

# 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 frm 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

#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!"

User-defined Function (Create 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.

A function is a block of code which only runs when it is called.


You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function

To create a function, use the function() keyword:

Example
my_function <- function() { # create a function with the name
my_function
print("Hello World!")
}
Call a Function

To call a function, use the function name followed by parenthesis,


like my_function():

Example
my_function <- function() {
print("Hello World!")
}

my_function() # call the function named my_function


Examples:-
# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
# Create a function to print squares of numbers in sequence.
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)
When we execute the above code, it produces the following result −
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36

Function arguments and default values:-


Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a
comma.
The following example has a function with one argument (fname). When
the function is called, we pass along a first name, which is used inside the
function to print the full name:

my_function <- function(fname) {


paste(fname, "Griffin")
}

my_function("Peter")
my_function("Lois")
my_function("Stewie")

Output:-
[1] "Peter Griffin"
[1] "Lois Griffin"
[1] "Stewie Griffin"

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.
new.function <- function(a = 3, b = 6) {
result <- a * b
print(result)
}

# Call the function without giving any argument.


new.function()

# Call the function with giving new values of the argument.


new.function(9,5)
When we execute the above code, it produces the following result −
[1] 18
[1] 45
Number of Arguments:-

By default, a function must be called with the correct number of


arguments. Meaning that if your function expects 2 arguments, you have
to call the function with 2 arguments, not more, and not less:

Example 1

This function expects 2 arguments, and gets 2 arguments:

my_function <- function(fname, lname) {


paste(fname, lname)
}

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

This function expects 2 arguments, and gets 1 argument:

my_function <- function(fname, lname) {


paste(fname, lname)
}

my_function("Peter")
Example 2

# Create a function with arguments.


new.function <- function(a, b) {
print(a^2)
print(a)
print(b)
}

# Evaluate the function without supplying one of the arguments.


new.function(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

** Note :- Parameters or Arguments?


The terms "parameter" and "argument" can be used for the
same thing: information that are passed into a function.

From a function's perspective:

A parameter is the variable listed inside the parentheses in the


function definition.

An argument is the value that is sent to the function when it is


called.

Example:

# A simple R program to demonstrate


# passing arguments to a function

Rectangle = function(length=5, width=4)


{
area = length * width
return(area)
}

# Case 1:
print(Rectangle(2, 3))
# Case 2:
print(Rectangle(width = 8, length = 4))

# Case 3:
print(Rectangle())

Output
6
32
20

You might also like