KEMBAR78
R Language Unit 1 | PDF | Control Flow | Statistics
0% found this document useful (0 votes)
10 views21 pages

R Language Unit 1

Uploaded by

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

R Language Unit 1

Uploaded by

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

DATA ANALYTICS USING R

UNIT-I: INTRODUCTION
Features of R, Variables, Constants, Datatypes, Operators: Arithmetic Operators, Relational
Operators, Logical Operator, Assignment Operators, Miscellaneous Operators, Decision Making: if
statement, if – else statement, if – else if statement, switch statement – Loops: repeat loop, while
loop, for loop - Loop control statement: break statement, next statement.

INTRODUCTION TO R

R is a programming language and software environment for statistical analysis, graphics


representation, data visualization and reporting. R is an interpreted programming language widely
used for statistical computing, data analysis and visualization. R language is open-source with
large community support. R provides structured approach to data manipulation, along with decent
libraries and packages

FEATURES OF R

 It is a great resource for data analysis, data visualization, data science and machine learning
 It provides many statistical techniques (such as statistical tests, classification, clustering and
data reduction)
 It is easy to draw graphs in R, like pie charts, histograms, box plot, scatter plot, etc.
 It works on different platforms (Windows, Mac, Linux)
 It is open-source and free
 It has a large community support
 It has many packages (libraries of functions) that can be used to solve different problems

1. Open Source and Free


R is free to download and use.
It is open-source, meaning anyone can view, modify, and distribute the code.
2. Designed for Statistical Computing
R is specially built for statistics and data analysis.
Supports statistical techniques like regression, hypothesis testing, time series analysis, etc.
3. Wide Range of Packages
Thousands of libraries available for various purposes.
Popular packages include:
ggplot2 – for data visualization
dplyr – for data manipulation
caret – for machine learning
shiny – for web application
4. Excellent Data Visualization
R can produce high-quality graphs and charts.
You can create line charts, bar graphs, scatter plots, pie charts, and interactive dashboards.
5. Advanced Data Handling
R supports various data structures:
Vectors, Matrices, Data Frames, Lists, Factors and Array
Handles large datasets efficiently.
6. Cross-platform Support
R runs on Windows, Linux, and macOS.
Code written on one system can run on another without changes.
7. Easy Integration
R can work with:
Databases (MySQL, SQLite)
Excel files
Web APIs
Other programming languages like Python, C++, and Java
8. Supports Machine Learning & AI
R includes functions and libraries for:
Classification
Clustering
Decision trees
Neural networks
9. Built-in Functions for Quick Analysis
R has many pre-defined functions like:
mean(), median(), sd() for statistics
summary() to get quick data insights
Saves time and makes analysis faster.
10. Interactive Web Applications with Shiny
R can build interactive web apps using the Shiny package.
Useful for creating dynamic dashboards and data tools without needing web development
knowledge.

COMMENTS

Comments are portions of a computer program that are used to describe a piece of code.
Comments have nothing to do with code logic. They do not get interpreted or compiled and are
completely ignored during the execution of the program.

Comments are two types: single-line comment and multi-line comment


You use the # symbol to create both single-line and multi-line comments in R.

For example,
# this is single-line comment
print("Hello World")
# this is multi-line comment
# it prints Hello World
print("Hello World")
VARIABLES

Variables are containers for storing data values. R does not have a command for declaring a
variable. A variable is created the moment you first assign a value to it. To assign a value to a
variable, use the <- sign. A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume). To output (or print) the variable value, just type the variable name:

Example:

name <- "John" output


age <- 40 "John"
print(name) 40
print(age)

RULES FOR R VARIABLES ARE:

 A variable name must start with a letter and can be a combination of letters, digits, period(.)
and underscore(_). If it starts with period(.), it cannot be followed by a digit.
 A variable name cannot start with a number or underscore (_)
 Variable names are case-sensitive (age, Age and AGE are three different variables)
 Reserved words cannot be used as variables (TRUE, FALSE, NULL, if...)

# Legal variable names:

 myvar<- "John"
 my_var<- "John"
 myVar<- "John"
 MYVAR <- "John"
 myvar2 <- "John"
 .myvar<- "John"

# Illegal variable names:

 2myvar <- "John"


 my-var<- "John"
 my var<- "John"
 _my_var<- "John"
 my_v@ar<- "John"
 TRUE <- "John"

MULTIPLE VARIABLES

R allows you to assign the same value to multiple variables in one line:

Example:

var1 <- var2 <- var3 <- "Orange"


TYPES OF VARIABLES

Depending on the type of data that you want to store, variables can be divided into the following
types.
1. Boolean Variables
2. Integer Variables
3. Floating Point Variables
4. Character Variables
5. String Variables

1. Boolean Variables:
It stores single bit data which is either TRUE or FALSE. Here, TRUE means yes and FALSE
means no. For example,

a = TRUE Output:
print(a) [1] TRUE
print(class(a)) [1] "logical"

Here, we have declared the boolean variable a with the value TRUE. Boolean variables belong to the
logical class so class(a) returns "logical".

2. Integer Variables:
It stores numeric data without any decimal values. For example,

A = 14L Output:
print(A) [1] 14
print(class(A)) [1] "integer"

Here, L represents integer value. In R, integer variables belong to the integer class so, class(a)
returns "integer".

3. Floating Point Variables:


It stores numeric data with decimal values. For example,

x = 13.4 Output:
print(x) [1] 13.4
print(class(x)) [1] "numeric”

Here, we have created a floating point variable named x. You can see that the floating point variable
belongs to the numeric class.

4. Character Variables:
It stores a single character data. For example,
alphabet = "a" Output:
print(alphabet) [1] "a"
print(class(alphabet)) [1] "character"
Here, we have created a character variable named alphabet. Since character variables belong to the
character class, class(alphabet) returns "character".

5. String Variables:
It stores data that is composed of more than one character. We use double quotes to represent
string data. For example,

message = "Welcome to Programming Output:


World!" [1] "Welcome to Programming World!"
print(message) [1] "character"
print(class(message))

Here, we have created a string variable named message. You can see that the string variable also
belongs to the character class.

Changing Value of Variables:


Depending on the conditions or information passed into the program, you can change the
value of a variable. For example,
message = "Hello World!" Output:
print(message)
# changing value of a variable [1] "Hello World!"
message <- "Welcome to Programming World!" [1] "Welcome to Programming World!"
print(message)

In this program,
"Hello World!" - initial value of message
"Welcome to Programming World!" - changed value of message

CONSTANTS
Constants are those entities whose values aren't meant to be changed anywhere throughout the
code. Constants are also known as scalars. In R, we can declare constants using the <- symbol. For
example,
Output:
x <- "Welcome to Programming World!" [1] "Welcome to Programming World!"
print(x) Here, "Welcome to Programming World!" is a
string constant.

TYPES OF R CONSTANTS
In R, we have the following types of constants.

The five types of R constants are

 Numeric
 Integer
 Complex
 Logical
 String
In addition to these, there are 4 specific types of R constants
 Null
 NA
 Inf,
 NaN.

1. Integer Constants:
Integer constants are the integer values we use in our code. These constants end with the letter
L. For example,
x <- 15L Output:
print(typeof(x)) [1] "integer"
print(class(x)) [1] "integer"

Here, 15L is a constant which has been assigned to x. You can see that the type and class of the
constant is integer.
We can use different types of integer constants in our code. For example,

# hexadecimal value Output:


x <- 0x15L [1] 21
print(x)

# exponential value
x <- 1e5L [1] 100000
print(x)

2. Numeric Constants:
In R programming, numeric constants can be integers (4), floating-point numbers (0.55), or
exponential numbers (3e-3). For example,

z <- 3e-3 Output:


print(z) # 0.003
print(class(z)) # "numeric" [1] 0.003
[1] "numeric"
y <- 3.4
print(y) # 3.4 [1] 3.4
print(class(z)) # "numeric" [1] "numeric"

3. Logical Constants
Logical constants in R are either TRUE or FALSE. For example,
x <- TRUE Output:
y <- FALSE
print(x) [1] TRUE
print(y) [1] FALSE

Note: We can also use a single character to create logical constants. For example,
x <- T
print(x) # TRUE
4. String Constants

String constants are the string data we use in our code. For example,

message <- "Welcome to Programming World!!" Output:


print(message) [1] "Welcome to Programming World!!"

5. Complex Constants:

A complex constant is data that contains a real and an imaginary part (denoted by the suffix
i). For example,
y <- 3.2e-1i Output:
print(y) [1] 0+0.32i
print(typeof(y)) [1] "complex"
Note: Complex constants can only be purely imaginary. For example,

y <- 3i
print(y) # 0+3i
print(typeof(y)) # "complex"

Special R Constants:
R programming also provides 4 special types of constants.
1. NULL
2. Inf/-Inf
3. NaN (Not a Number)
4. NA

1. NULL - to declare an empty R object. For example,


x <- NULL
print(x) # NULL
print(typeof(x)) # "NULL"

2. Inf/-Inf - represents positive and negative infinity. For example,


# result is too big so it represents positive infinity
a <- 2^2020
print(a) # Inf

# result is too big


b <- -2^2020
print(b) # -Inf

3. NaN (Not a Number) - represents undefined numerical value. For example,


print(0/0) # NaN
print(Inf/Inf) #NaN

4. NA - represents value which is not available. For example,


print(NA + 20) # NA
Built-In R Constants:

R programming provides some predefined constants that can be directly used in our program.
 LETTERS - to display a list of all uppercase letters
 letters - to display a list of all small letters
 month.abb - to print 3 letter abbreviations of all English months
 pi - to print the numerical value of the constant pi

For example,

# print list of uppercase letters


print(LETTERS)

# print list of lowercase letters


print(letters)

# print 3 letters abbreviation of English months


print(month.abb)

# print numerical value of constant pi


print(pi)

Output

[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[20] "T" "U" "V" "W" "X" "Y" "Z"
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
[1] 3.141593

DATA TYPES

Data types in R define the kind of values that variables can hold. A variable can store
different types of values such as numbers, characters etc. These different types of data that we can
use in our code are called data types. For example,

x <- 123L
Here, 123L is an integer data. So the data type of the variable x is integer.

We can verify this by printing the class of x.


x <- 123L Output:
# print value of x
print(x) [1] 123
# print type of x [1] "integer"
print(class(x)) Here, x is a variable of data type integer.
DIFFERENT TYPES OF DATA TYPES

In R, there are 6 basic data types:

 Logical
 Numeric
 Integer
 Complex
 Character

1.Logical Data Type

The logical data type in R is also known as Boolean data type. It can only have two values:
TRUE and FALSE. For example,

bool1 <- TRUE Output


print(bool1)
print(class(bool1)) [1] TRUE
[1] "logical"
bool2 <- FALSE [1] FALSE
print(bool2) [1] "logical"
print(class(bool2))

In the above example, bool1 has the value TRUE, bool2 has the value FALSE.
Here, we get "logical" when we check the type of both variables.

Note: You can also define logical variables with a single letter - T for TRUE or F for FALSE.
For example,

is_weekend<- F Output:
print(class(is_weekend)) [1]"logical"

2. Numeric Data Type

In R, the numeric data type represents all real numbers with or without decimal values. For
example,

# floating point values Output:


weight <- 63.5
print(weight) [1] 63.5
print(class(weight)) [1] "numeric"
[1] 182
# real numbers [1] "numeric"
height <- 182 Here, both weight and height are variables of
print(height) numeric type.
print(class(height))
3. Integer Data Type
The integer data type specifies real values without decimal points. We use the suffix “L” to
specify integer data. For example,

integer_variable<- 186L Output


print(class(integer_variable)) [1] "integer"

Here, 186L is an integer data. So we get "integer" when we print the class of integer_variable.

4. Complex Data Type

The complex data type is used to specify purely imaginary values in R. We use the suffix i to
specify the imaginary part. For example,

# 2i represents imaginary part Output:


complex_value<- 3 + 2i
[1] "complex"
# print class of complex_value Here, 3 + 2i is of complex data type because it
print(class(complex_value)) has an imaginary part 2i

5. Character Data Type

The character data type is used to specify character or string values in a variable.In
programming, a string is a set of characters. For example, 'A' is a single character and "Apple" is a
string. In general, we use:

single quotes (' ') for character variables


double quotes (" ") for string variables
For example,

# create a string variable Output:


fruit <- "Apple"
print(class(fruit)) [1] "character"
[1] "character"
# create a character variable
my_char<- 'A'
print(class(my_char))

Here, both the variables - fruit and my_char - are of character data type.

Examples for all data types:


# Numeric (double)
num<- 3.14
print(paste("Numeric:", num)) # "Numeric: 3.14"
print(typeof(num)) # "double"
print(mode(num)) # "numeric"
print(class(num)) # "numeric"
# Integer # Logical
int<- 42L logic<- TRUE
print(paste("Integer:", int)) #"Integer: 42" print(paste("Logical:", logic)) #"Logical:
print(typeof(int)) # "integer" TRUE"
print(mode(int)) # "numeric" print(typeof(logic)) # "logical"
print(class(int)) # "integer" print(mode(logic)) # "logical"
print(class(logic)) # "logical"
# Character # Complex
char <- "Hello R" comp <- 2 + 3i
print(paste("Character:", char)) #"Character: print(paste("Complex:", comp)) # "Complex:
Hello R" 2+3i"
print(typeof(char)) # "character" print(typeof(comp)) # "complex"
print(mode(char)) # "character" print(mode(comp)) # "complex"
print(class(char)) # "character” print(class(comp)) # "complex"

CHECKING DATA TYPES IN R

FUNCTION DESCRIPTION EXAMPLE


class() Returns the class of an object class(42) → "numeric"
typeof() Returns the internal type of an object typeof(42) → "double"
mode() Returns the general type of data mode(42) →"numeric"
is.numeric() Checks if the object is numeric is.numeric(3.14) → TRUE
is.integer() Checks if the object is integer is.integer(10L) → TRUE
is.character() Checks for character x <- "Hello"
is.character(x) →TRUE
is.logical() Checks for logical values (TRUE, FALSE) is.logical(TRUE) → TRUE
is.complex() Checks if it's a complex number is.complex(1+2i) → TRUE
is.vector() Checks if it's a vector is.vector(c(1,2,3)) → TRUE
is.matrix() Checks if it's a matrix is.matrix(matrix(1:4, 2, 2))
is.data.frame() Checks if it's a data frame is.data.frame(data.frame(x=1))
is.factor() Checks if it's a factor (categorical) is.factor(factor("a"))
is.array() Checks if it's an array is.array(array(1:8, c(2,2,2)))
is.list() Checks if it's a list y <- list(1, "a", TRUE)
is.list(y) →TRUE
is.raw() Checks for a raw type z <- as.raw(255)
is.raw(z)→TRUE
is.na() Checks if a value is NA(missing) is.na(NA) → TRUE
is.null() Checks if a value is NULL is.null(NULL) → TRUE
OPERATORS
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations.Operators are the symbols directing the compiler to perform various kinds of
operations between the operands. Operators simulate the various mathematical, logical, and decision
operations performed on a set of Complex Numbers, Integers, and Numericals as input operands.
R divides the operators in the following groups:
 Arithmetic operators
 Comparison operators or Relational operators
 Logical operators
 Assignment operators
 Miscellaneous operators
1. Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical
operations.
Operator Operation Description
+ Addition Adds two value
- Subtraction Subtracts second value from the first
* Multiplication Multiplies both values
/ Division Divide the first value with the second
^ Exponent The first value raised to the exponent of second value
%% Modulus Give the remainder of the first value with the second
The result of division of first value with second
%/% Integer Division
(quotient)

Examples:
x <- 5
y <- 16
x+y #Addition
[1] 21
x-y #Subtraction
[1] -11
x*y #Multiplication
[1] 80
y/x#Division
[1] 3.2
y^x#Exponent
[1] 1048576
y%%x#Modulus
[1] 1
y%/%x #Integer Division
[1] 3
2. Relational Operators or Comparison Operators
The Relational Operators in R carry out comparison operations between the corresponding
elements of the operands. Returns a boolean TRUE value if the first operand satisfies the relation
compared to the second. A TRUE value is always considered to be greater than the FALSE.
Comparison operators are used to compare two values.

Operator Operation Description


Checks if the first value is equal to the second
== Equal
value.
Checks if the first value is not equal to the
!= Not equal
second value.
Checks if the first value is greater than the
> Greater than
second value.
Checks if the first value is less than the second
< Less than
value.
Checks if the first value is greater than or
>= Greater than or equal to
equal to the second value.
Checks if the first value is less than or equal to
<= Less than or equal to
the second value.

Examples:
x <- 5
y <- 16
x<y#Less than
[1] TRUE
x>y #Greater than
[1] FALSE
x<=5#Less than or equal to
[1] TRUE
y>=20#Greater than or equal to
[1] FALSE
y == 16#Equal
[1] TRUE
x != 5#Not equal
[1] FALSE

3. Logical Operators
Logical Operators in R simulate element-wise decision operations, based on the specified
operator between the operands, which are then evaluated to either a True or False boolean value.
Any non-zero integer value is considered as a TRUE value, be it a complex or real number. Logical
operators are used to combine conditional statements.
Operator Operation Description
& Element-wise Logical AND operator Returns TRUE if both statements are TRUE
Returns TRUE if the both first elements of
&& Logical AND operator (short-circuit)
the statements are TRUE
Returns TRUE if one of the statements is
| Element-wise Logical OR operator
TRUE
Returns TRUE if one of the first element of
|| Logical OR operator (short-circuit)
the statements is TRUE
! Logical NOT Returns FALSE if statement is TRUE
Examples:
x <- c(TRUE,FALSE,0,6)
y <- c(FALSE,TRUE,FALSE,TRUE)
x&y#Element-wise Logical AND operator
[1] FALSE FALSEFALSE TRUE
x[1] && y[1] #Logical AND operator (short-circuit)
[1] FALSE
x|y #Element-wise Logical OR operator
[1] TRUETRUE FALSE TRUE
x[1] || y[1]#Logical OR operator (short-circuit)
[1] TRUE
!x#Logical NOT
[1] FALSE TRUETRUE FALSE

4.Assignment Operator
Assignment operators are used to assign values to variables.
Operator Operation Description
<-, <<-, = Left Assignment Assigns a value to a variable
->, ->> Right assignment Assigns value to a variable
Examples:
my_var<- 3 #Left Assignment
my_var<<- 3 #Left Assignment
my_var=3 #Left Assignment
3 ->my_var #Right Assignment
3 ->>my_var #Right Assignment
my_var
[1] 3

5.Miscellaneous Operator
Miscellaneous operators are used to manipulate data.
Operator Description
: Creates a series of numbers in a sequence
%in% Find out if an element belongs to a vector
%*% Matrix Multiplication
Examples:
x <- 1:5 # : operator A <- matrix(1:4, nrow=2)
print(x) B <- matrix(1:4, ncol=2)
[1] 1 2 3 4 5 print(A %*% B) # %*% operator
[,1] [,2]
print(2 %in% c(1, 2, 3)) # %in% operator [1,] 7 15
[1] TRUE [2,] 10 22

DECISION MAKING
Decision making allows us to control the flow of execution based on specific conditions.
Decision making in R allows the program to choose different paths of execution based on one or
more conditions.These statements help in performing different actions depending on whether a
condition is true or false. In R, various decision-making structures help us execute statements
conditionally. These include:
1. if statement
2. if-else statement
3. if-else-if ladder
4. nested if-else statement
5. switch statement
1. if Statement:
The if statement evaluates a condition. If the condition is TRUE, the associated statement is
executed. If the condition is FALSE, the statement is skipped.
Syntax:
if (condition)
{
# execute this statement
}
Here, the condition is a boolean expression. It returns either TRUE or FALSE.
 If the condition is TRUE – the code inside the if block (body of the if statement) is
executed.
 If the condition is FALSE – the code inside the block is skipped, and R moves to the next
line after the if statement.
Example:
x <- 10 Output:
if (x > 5) { [1] "x is greater than 5"
print("x is greater than 5")
}

2. if-else Statement
The if-else statement executes one block if the condition is TRUE and another if it is
FALSE.
Syntax:
if (condition) {
# execute this statement
} else {
# execute this statement
}
Here, the condition is a boolean expression. It returns either TRUE or FALSE.
 If the condition is TRUE – the code inside the if block is executed.
 If the condition is FALSE – the code inside the else block is executed.
Only oneblock is executed depending on the condition.
Example:
x <- 3 Output:
if (x > 5) { [1] "Less than or equal to 5"
print("Greater than 5")
} else {
print("Less than or equal to 5")
}
3. if-else-if Ladder:
This structure chains multiple conditions together. Each condition is evaluated in sequence.
If a condition is TRUE, its block is executed. Otherwise, the next condition is checked.
Syntax:
if (condition1) {
# execute this statement
} else if (condition2) {
# execute this statement
} else {
# execute this statement
}
Here, the condition1 and condition2 are booleanexpressions that return either TRUE or FALSE.
 If condition1 is TRUE, only the if block is executed, and the rest is skipped.
 If condition1 is FALSE, but condition2 is TRUE – the else if block is executed.
 IfneitherconditionisTRUE – the final else block is executed.
 Only one block is executed, based on the first condition that evaluates to TRUE
Example:
x <- 0 Output:
if (x > 0) { [1] "Zero"
print("Positive")
} else if (x < 0) {
print("Negative")
} else {
print("Zero")
}
4. Nested if-else Statement
Nested if-else statements are used when one condition needs to be checked inside another. If
the parent condition is TRUE, the child condition is evaluated.
Syntax:
if (parent_condition) {
if (child_condition1) {
# execute this statement
} else {
# execute this statement
}
} else {
if (child_condition2) {
# execute this statement
} else {
# execute this statement
}
}
Here, there are three if conditions, one outer if and two inner if conditions.So, this is a nested
structure with three decision-making statements:an outer if, and two inner if...else blocks, one
inside the if part and one inside the else part.
 The outer if...else is controlled by parent_condition.
 If parent_condition is TRUE, then it goes inside the if…else block and checks
child_condition1.
 If child_condition1 is TRUE, the first inner block is executed.
 Otherwise, the else block under it is executed.
 If parent_condition is FALSE, it checks the else part where child_condition2 is evaluated.
 If child_condition2 is TRUE, its block runs.

 If child_condition2 is FALSE, the final else block runs.


Example:
x <- -12 Output:
if (x >= 0) { [1] "x is Very Negative"
if (x == 0) {
print("x is Zero")
} else {
print("x is Positive")
}
} else {
if (x < -10) {
print("x is Very Negative")
} else {
print("x is Negative")
}}
5. Switch Statement:
The switch statement compares an expression to a list of possible cases. If a match is found,
the corresponding case is executed. If no match is found, it returns NULL.
Syntax:
switch(expression, case1, case2, case3, ..., caseN)
Here, the expression is usually a number or a characterstring.
 If the expression is a number (e.g., 2), then switch() returns the value at that position (2nd
case).
 If the expression is a string (e.g., "apple"), then it returns the value of the matching named
case.
 If there is nomatch, it returns NULL.
Example:
day_num<- as.integer(readline("Enter a number (1 to 7): ")) Output:
day_name<- switch(day_num, Enter a number (1 to 7): 3
"Sunday", # 1 [1] "Day is: Tuesday"
"Monday", # 2
"Tuesday", # 3
"Wednesday", # 4
"Thursday", # 5
"Friday", # 6
"Saturday" # 7)
print(paste("Day is:", day_name))

LOOPS

In R, Loops are control flow structures that allow you to repeat a set of instructions multiple
times, either for a fixed number of times or until a certain condition is met. They help automate
repetitive tasks, such as processing elements in a vector, performing calculations, or printing values.

Types of Loops:

1. For loop
2. While loop
3. Repeat loop

1. For Loop:

In R, for loop is useful to iterate over the elements of a list, data frame, vector, matrix, or any
other object. It means the for loop can be used to execute a group of statements repeatedly depending
upon the number of elements in the object. It is an entry-controlled loop, in this loop, the test
condition is tested first, then the body of the loop is executed, the loop body would not be executed
if the test condition is false.
Syntax:
for (var in vector)
{
statements
}
 var→ A temporary loop variable which takes each value from the vector.
 vector → A collection of values (like a list, vector, or sequence).
 Each time, R picks the next value from vector, assigns it to var, and runs the code inside the
loop.
 This continues until all elements in the vector are processed.
Example:
for (i in c(-8, 9, 11, 45)){ Output:
print(i) [1] -8
} [1] 9
[1] 11
[1] 45

Nested For-loop:
R programming language allows using one loop inside another loop. In loop nesting, we can
put any type of loop inside of any other type of loop. For example, a for loop can be inside a while
loop or vice versa.
Example:
for (i in 1:3){ Output:
for (j in 1:i){ [1] 1
print(i * j) [1] 2
} [1] 4
} [1] 3
[1] 6
[1] 9

2. While loop:
While loop in R programming language is used when the exact number of iterations of a
loop is not known beforehand. It executes the same code again and again until a stop condition is
met. While loop checks for the condition to be true or false n+1 times rather than n times. This is
because the while loop checks for the condition before entering the body of the loop.
Syntax:
while (test_expression)
{
statement
update_expression
}
 test_expression: A logical (boolean) condition.
If it is TRUE, the loop body is executed.
If it is FALSE, the loop stops.
 statement: The code block that will run again and again as long as test_expression is true.
 update_expression: Usually a variable update that brings the loop closer to ending.
Without this, the loop may become infinite.
Example:
result <- c("Hello World") Output:
i<- 1 [1] "Hello World"
while (i< 6) { [1] "Hello World"
print(result) [1] "Hello World"
i=i+1 [1] "Hello World"
} [1] "Hello World"

3. Repeat Loop:
Repeat loop in R is used to iterate over a block of code multiple number of times. And also
it executes the same code again and again until a break statement is found. Repeat loop, unlike
other loops, doesn't use a condition to exit the loop instead it looks for a break statement that
executes if a condition within the loop body results to be true. An infinite loop in R can be created
very easily with the help of the Repeat loop. The keyword used for the repeat loop is 'repeat'.
Syntax:
repeat {
commands
if(condition) {
break
}
}
 repeat → Starts an infinite loop (it runs forever unless stopped manually).
 commands → The set of statements to execute repeatedly.
 if (condition) → A conditional check placed inside the loop.
 break → Used to exit the loop when the condition becomes TRUE.
Since repeat has no built-in stopping condition, you must use a break inside, or it will create an
infinite loop.
Example:
result <- c("Hello World") Output:
i<- 1 [1] "Hello World"
repeat { [1] "Hello World"
print(result) [1] "Hello World"
i<- i + 1 [1] "Hello World"
if(i>5) { [1] "Hello World"
break
}
}
LOOP CONTROL STATEMENTS
Loop control statements in R are used to change the normal flow of loops.
Types of Loop Control Statements:
i. Break Statement
ii. Next Statement
1.Break Statement:
The break statement in R is used to terminate the execution of a loop (like for, while, or
repeat) immediately. Even if the loop condition is still true, it will stop any further iterations.
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.
Syntax:
break
“break” is a standalone keyword. When the R interpreter encounters a break, it immediately
exits the loop. Any code after the break inside the loop block will not be executed.
Example:
# Print numbers from 1 to 10, but stop at 5 Output:
for (i in 1:10) { [1] 1
if (i == 6) { [1] 2
break # Exit the loop when i is 6 [1] 3
} [1] 4
print(i) [1] 5
}
2. Next Statement:
The next statement in R is used to skip the current iteration in the loop and move to the next
iteration without exiting from the loop itself.
Syntax: next
If the program encounters the next statement, any further execution of code from the current iteration is
skipped, and the next iteration begins.

Example:
# Print numbers from 1 to 5, but skip 3 Output:
for (i in 1:5) { [1] 1
if (i == 3) { [1] 2
next # Skip the rest of the loop when i is 3 [1] 4
} [1] 5
print(i)}

You might also like