R-Loops and Functions
R-Loops and Functions
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
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
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
• # 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.