0% found this document useful (0 votes)
19 views40 pages

R-Loops and Functions

The document provides an overview of loops in R programming, detailing three types: Repeat, While, and For loops, along with their syntax and examples. It also discusses loop control statements like break and next, as well as the concept of functions, including built-in and user-defined functions, and how to pass arguments. Additionally, it touches on R packages, which are collections of functions and data stored in a library directory.

Uploaded by

manu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views40 pages

R-Loops and Functions

The document provides an overview of loops in R programming, detailing three types: Repeat, While, and For loops, along with their syntax and examples. It also discusses loop control statements like break and next, as well as the concept of functions, including built-in and user-defined functions, and how to pass arguments. Additionally, it touches on R packages, which are collections of functions and data stored in a library directory.

Uploaded by

manu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

R-Loops

There are three types of loop in R programming:


1.Repeat Loop
2.While Loop
3.For Loop
repeat loop
• Executes a sequence of statements multiple
times and abbreviates the code that manages
the loop variable.
• The Repeat loop executes the same code again
and again until a stop condition is met.
Syntax
• The basic syntax for creating a repeat loop in R is
• repeat {
commands
if(condition)
{
break
}
}
• v<-c("GRIET","DS")
• > cnt<-2
• > repeat
{
print(v)
cnt<-cnt+1
if(cnt>5)
{
break
}
}
Output
• [1] "GRIET" "DS"
• [1] "GRIET" "DS"
• [1] "GRIET" "DS"
• [1] "GRIET" "DS"
val = 1

repeat
{
print(val)
val = val + 1
if(val > 5)
{
break
}
}
i=0
repeat
{
print("Data Science")
i=i+1
if(i==5)
{
break
}
}
• [1] "Data Science"
• [1] "Data Science"
• [1] "Data Science"
• [1] "Data Science"
• [1] "Data Science"
• >
while loop
• Repeats a statement or group of statements
while a given condition is true. It tests the
condition before executing the loop body.
• The While loop executes the same code again and
again until a stop condition is met.
Syntax
• The basic syntax for creating a while loop in R is −
• while (test_expression)
{
statement
}
• Example
v <- c("Hello","Welcome to GRIET")
cnt <- 2
while (cnt < 7)
{
print(v)
cnt = cnt + 1
}
OUTPUT:
[1] "Hello" "Welcome to GRIET"
[1] "Hello" "Welcome to GRIET"
[1] "Hello" "Welcome to GRIET"
[1] "Hello" "Welcome to GRIET"
[1] "Hello" "Welcome to GRIET"
val = 1

while (val <= 5)


{

print(val)
val = val + 1
}
Program to calculate factorial of a number

n=5
factorial=1
i=1
while (i <= n)
{
factorial = factorial * i
i=i+1
}
print(factorial)
for loop
• Like a while statement, except that it tests the
condition at the end of the loop body.
• A For loop is a repetition control structure that allows
you to efficiently write a loop that needs to execute a
specific number of times.
Syntax
• The basic syntax for creating a for loop statement in R
is −
for (value in vector)
{
statements
}
R’s for loops are particularly flexible in that they are not limited to integers, or even
numbers in the input. We can pass character vectors, logical vectors, lists or
expressions.
• Example:
v <- LETTERS[1:4]
for ( i in v)
{
print(i)
}
[1] "A"
[1] "B"
[1] "C“
[1] "D"
for (val in 1: 5)
{
print(val)
}
Program to display days of a week.
week =
c('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')
> for(day in week)
{
print(day)
}
[1] "Sunday"
[1] "Monday"
[1] "Tuesday"
[1] "Wednesday"
[1] "Thursday"
[1] "Friday"
[1] "Saturday"
Loop Control Statements

• Loop control statements change execution from its


normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are
destroyed.
break statement
• Terminates the loop statement and transfers execution
to the statement immediately following the loop
Next statement
• The next statement simulates the behavior of R switch.
The break statement in R programming language has
the following two usages −
• When the break statement is encountered inside a
loop, the loop is immediately terminated and
program control resumes at the next statement
following the loop.
• It can be used to terminate a case in the switch
statement
• The next statement in R programming
language is useful when we want to skip the
current iteration of a loop without terminating
it. On encountering next, the R parser skips
further evaluation and starts next iteration of
the loop.
for (val in 1: 5)
{
if (val == 3)
{
next
}
print(val)
}
• [1] 1
• [1] 2
• [1] 4
• [1] 5
v<-LETTERS[1:6)]
for (i in v)
{
if(i=="D")
{
print(i)
}
Functions in R Programming
• Functions are useful when you want to
perform a certain task multiple times.
Types of function in R Language
• Built-in Function: Built function R is sq(),
mean(), max(), these function are directly call
in the program by users.
• User-define Function: R language allow us to
write our own function.
Functions in R Language
Functions are created in R by using the
command function(). The general structure of
the function file is as follows:
f=function(arguments)
{
Statements
}
• Here F =Function name
Built-in Function in R Programming Language

Here we will use built-in function like


• sum(),
• max() and min().
print(sum(4:6))
print(max(4:6))
print(min(4:6))
User-defined Functions in R Programming Language

evenOdd = function(x){
if(x %% 2 == 0)
return("even")
else
return("odd")
}
print(evenOdd(4))
print(evenOdd(3))
Single Input Single Output

areaOfCircle = function(radius){
area = pi*radius^2
return(area)
}
print(areaOfCircle(2))
Multiple Input Multiple Output

Rectangle = function(length, width)


{
area = length * width
perimeter = 2 * (length + width)
result = list("Area" = area, "Perimeter" = perimeter)
return(result)
}
resultList = Rectangle(2, 3)
print(resultList["Area"])
print(resultList["Perimeter"])
Inline Functions in R Programming Language

• Sometimes creating an R script file, loading it,


executing it is a lot of work when you want to
just create a very small function. So, what we
can do in this kind of situation is an inline
function.
• To create an inline function you have to use
the function command with the argument x
and then the expression of the function.
f = function(x) x^2*4+x/3
print(f(4))
print(f(-2))
print(0)
Passing arguments to Functions in R Programming Language

• There are several ways you can pass the arguments to


the function:
• Case 1: Generally in R, the arguments are passed to
the function in the same order as in the function
definition.
• Case 2: If you do not want to follow any order what
you can do is you can pass the arguments using the
names of the arguments in any order.
• Case 3: If the arguments are not passed the default
values are used to execute the 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())
R-Packages
R packages are the collection of R functions, sample
data, and compile codes. In the R environment, these
packages are stored under a directory called "library."
During installation, R installs a set of packages. We can
add packages later when they are needed for some
specific purpose. Only the default packages will be
available when we start the R console. Other packages
which are already installed will be loaded explicitly to
be used by the R program.

You might also like