SIP-I on (Day 3)
R Programming
By
Dr. Devanshu Tiwari
Assistant Professor
Centre for Computer Science and Business Management
MITS-DU, Gwalior
12/11/2024
Day 3 contents
Fundamentals of R
• R Strings
• R Booleans
• R Operators
• R If...Else
• R While Loop
• R For Loop
• R Functions
12/11/2024
Fundamentals of R
R Strings
• A string is a sequence of characters. For example, "Programming" is a
string that includes characters: P, r, o, g, r, a, m, m, i, n, g.
• In R, we represent strings using quotation marks (double quotes, " " or
single quotes, ' '). For example,
Here, both 'Hello' and "Hello" are strings. We can use either single quotes or double quotes
to represent strings in R.
However, we cannot mismatch them. For example, start the string with a single quote and
end it with a double quote, 'Hello" and vice versa, "Hello'.
12/11/2024
Fundamentals of R
R Strings
12/11/2024
Fundamentals of R
String Operations in R
R provides us various built-in functions that allow us to
perform different operations on strings. Here, we will look
at some of the commonly used string functions.
• Find the length of a string
• Join two strings
• Compare two strings
• Change the string case
12/11/2024
Fundamentals of R
String Operations in R
1. Find Length of R String
We use the nchar() method to find the length of a string. For
example,
12/11/2024
Fundamentals of R
String Operations in R
2. Join Strings Together
In R, we can use the paste() function to join two or more strings together. For example,
12/11/2024
Fundamentals of R
String Operations in R
3. Compare Two Strings in R Programming
We use the == operator to compare two strings. If two strings are equal, the operator
returns TRUE. Otherwise, it returns FALSE. For example,
12/11/2024
Fundamentals of R
String Operations in R
4. Change Case of R String
In R, we can change the case of a string using
•toupper() - convert string to uppercase
•tolower() - convert string to lowercase
12/11/2024
Fundamentals of R
Other String Functions
Escape Sequences in R String
The escape sequence is used to escape some of the characters present inside a string. Suppose we need to include
double quotes inside a string.
12/11/2024
Fundamentals of R
Other String Functions
Note: A double-quoted string can have single quotes without escaping them. For example,
12/11/2024
Fundamentals of R
Other String Functions
R Multiline String
In R, we can also create a multiline string. However, at the end of each line
break R will add "\n" to indicate a new line. For example,
In the above example, we have
created a multiline string and
stored it in message1. Here, we
have used the print() function
to print the string.
You can see we are getting \n
at the end of each line break.
12/11/2024
Fundamentals of R
Other String Functions
R Multiline String
However, if we want to print the actual string without \n at end, we can use cat()
instead of print. For example,
12/11/2024
Fundamentals of R
Other String Functions
R Multiline String
However, if we want to print the actual string without \n at end, we can use cat()
instead of print. For example,
12/11/2024
Fundamentals of R
R Boolean
• In programming, you often need to know if an expression is true or false.
• You can evaluate any expression in R, and get one of two answers, TRUE or FALSE.
• When you compare two values, the expression is evaluated and R returns the logical answer:
You can also compare two variables:
12/11/2024
Fundamentals of R
R Boolean
• You can also run a condition in an if statement
Example
a <- 200
b <- 33
if (b > a) {
print ("b is greater than a")
} else {
print("b is not greater than a")
}
12/11/2024
Fundamentals of R
R Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
R divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Miscellaneous operators
12/11/2024
Fundamentals of R
R Operators
R Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
Note: Now
you have use
all these
arithmetic
operators in R
studio.
12/11/2024
Fundamentals of R
R Operators
R Assignment Operators
Assignment operators are used to assign values to variables:
Example
Note: <<- is a global
assigner.
It is also possible to turn the
direction of the assignment
operator.
x <- 3 is equal to 3 -> x
12/11/2024
Fundamentals of R
R Operators
R Comparison Operators
Comparison operators are used to compare two values:
Note: Now
you have use
all these
Comparison
operators in R
studio.
12/11/2024
Fundamentals of R
R Operators
R Logical Operators
Logical operators are used to combine conditional statements:
Note: Now
you have use
all these
Logical
operators in R
studio.
12/11/2024
Fundamentals of R
R Operators
R Miscellaneous Operators
Miscellaneous operators are used to manipulate data:
Note: Now
you have use
all these
Miscellaneous
operators in R
studio.
12/11/2024
Fundamentals of R
R If...Else
In computer programming, the if statement allows us to create a decision making program.
A decision making program runs one block of code under a condition and another block of code
under different conditions. For example,
If age is greater than 18, allow the person to vote.
If age is not greater than 18, don't allow the person to vote.
The syntax of an if statement is:
12/11/2024
Fundamentals of R
R If...Else
12/11/2024
Fundamentals of R
R If...Else
R if...else Statement
We can also use an optional else statement with an if statement. The syntax of an if...else statement is:
12/11/2024
Fundamentals of R
R If...Else
Since age is 16, the test expression is False. Hence, code inside the else statement is executed.
If we change the variable to another number. Let's say 31.
age <- 31
Now, if we run the program, the output will be:
[1] "You are eligible to vote."
12/11/2024
Fundamentals of R
R If...Else
12/11/2024
Fundamentals of R
R If...Else
12/11/2024
Fundamentals of R
R If...Else
12/11/2024
Fundamentals of R
R If...Else
12/11/2024
Fundamentals of R
R If...Else
In this program, the outer if...else block checks whether x is positive or negative. If x is
greater than 0, the code inside the outer if block is executed.
Otherwise, the code inside the outer else block is executed.
The inner if...else block checks whether x is even or odd. If x is perfectly divisible
by 2, the code inside the inner if block is executed. Otherwise, the code inside the
inner else block is executed.
12/11/2024
Fundamentals of R
R If...Else
R ifelse() Function
In R, the ifelse() function is a shorthand vectorized alternative to the
standard if...else statement.
Most of the functions in R take a vector as input and return a vectorized output. Similarly,
the vector equivalent of the traditional if...else block is the ifelse() function.
The syntax of the ifelse() function is:
The output vector has the element x if the output of the test_expression is TRUE. If the
output is FALSE, then the element in the output vector will be y.
12/11/2024
Fundamentals of R
R If...Else
Example 1: ifelse() Function for Odd/Even Numbers
Output
In this program, we have defined a vector x using the c() function in R. The vector contains a
few odd and even numbers. We then used the ifelse() function which takes the vector x as an
input. A logical operation is then performed on x to determine if the elements are odd or
even. For each element in the vector, if the test_expression evaluates to TRUE, then the
12/11/2024 corresponding output element is "EVEN", else it's "ODD".
Fundamentals of R
R If...Else
This program determines if the students have passed or failed based on a condition. Here, if the
marks in the vector are less than 40, then the student is considered to have failed.
12/11/2024
Fundamentals of R
R while Loop
In programming, loops are used to repeat a block of code as long as the specified condition
is satisfied. Loops help you to save time, avoid repeatable blocks of code, and write
cleaner code.
In R, there are three types of loops:
•while loops
•for loops
•repeat loops
12/11/2024
Fundamentals of R
R while Loop
R while Loop
while loops are used when you don't know the exact number of times a block of code is to
be repeated. The basic syntax of while loop in R is:
•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.
12/11/2024
Fundamentals of R
R while Loop
Example 1: R while Loop
Let's look at a program to calculate the sum of the first ten natural numbers.
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.
12/11/2024
Fundamentals of R
R while Loop
Example 2: while Loop With break Statement
The break statement in R can be used to stop the execution of a while loop even when the test
expression is TRUE. For example,
12/11/2024
Fundamentals of R
R while Loop
In this program, we have used a break statement inside the while loop, which breaks the loop as soon
as the condition inside the if statement is evaluated to TRUE.
Hence, the loop terminates when the number variable equals to 6. Therefore, only the
numbers 1 to 5 are printed.
12/11/2024
Fundamentals of R
R while Loop
Example 3: while Loop With next Statement
You can use the next statement in a while loop to skip an iteration even if the test condition is TRUE.
For example,
12/11/2024
Fundamentals of R
R while Loop
This program only prints the odd numbers in the range of 1 to 10. To do this, we have used
an if statement inside the while loop to check if number is divisible by 2.
Here,
if number is divisible by 2, then its value is simply incremented by 1 and the iteration is
skipped using the next statement.
if number is not divisible by 2, then the variable is printed and its value is incremented
by 1.
12/11/2024
Fundamentals of R
R Loop
R for Loop
A for loop is used to iterate over a list, vector or any other object of elements. The syntax of for loop
is:
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,
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. 12/11/2024
Fundamentals of R
R Loop
Example 1: Count the Number of Even Numbers
Let's use a for loop to count the number of even numbers stored inside a vector of numbers.
•In this program, we have used
a for loop to count the number of even
numbers in the num vector. Here is how
this program works:
•We first initialized the count variable
to 0. We use this variable to store the
count of even numbers in
the num vector.
•We then use a for loop to iterate
through the num vector using the
variable i.
12/11/2024
Fundamentals of R
R Loop
12/11/2024
Fundamentals of R
R Loop
Example 2: for Loop With break Statement
You can use the break statement to exit from the for loop in any iteration. For example,
Here, we have used
an if statement inside
the for loop. If the current
element is equal to 5, we break
the loop using
the break statement. After this,
no iteration will be executed.
12/11/2024
Fundamentals of R
R Loop
Example 3: for Loop With next Statement
Instead of terminating the loop, you can skip an iteration using the next statement. For example,
Here, we have used an if statement
inside the for loop to check for odd
numbers. If the number is odd, we
skip the iteration using
the next statement and print only
even numbers.
12/11/2024
Fundamentals of R
R Loop
Nested for Loops
You can include a for loop inside another for loop to create a nested loop.
Consider the example below. Suppose we have two sequences of numbers. We want to print all the
combinations where the sum of numbers in both the sequences is even.
In the above program, we have
created two
sequences: sequence_1 and sequenc
e_2, both containing numbers
from 1 to 3.
We then used a nested for loop to
iterate through the sequences. The
outer loop iterates
through sequence_1 and the inner
loop iterates through sequence_2
12/11/2024
Fundamentals of R
R Loop
In each iteration,
i stores the current number of sequence_1
j stores the current number of sequence_2
The if statement inside the nested loops checks if i + j is even or not. If it is, then we
print i and j.
12/11/2024
Fundamentals of R
R break and next
We use the R break and next statements to alter the flow of a program. These are also known as
jump statements in programming:
break - terminate a looping statement
next - skips an iteration of the loop
R break Statement
You can use a break statement inside a loop (for, while, repeat) to terminate the execution of the
loop. This will stop any further iterations.
The syntax of the break statement is:
12/11/2024
Fundamentals of R
R break and next
The break statement is often used inside a conditional (if...else) statement in a loop. If the condition inside
the test_expression returns True, then the break statement is executed. For example,
Here, we have defined a vector of
numbers from 1 to 7. Inside
the for loop, we check if the current
number is 4 using an if statement.
If yes, then the break statement is
executed and no further iterations are
carried out. Hence, only numbers
from 1 to 3 are printed.
12/11/2024
Fundamentals of R
R break and next
break Statement in Nested Loop
If you have a nested loop and the break statement is inside the inner loop, then the execution of
only the inner loop will be terminated.
12/11/2024
Fundamentals of R
R break and next
Here, we have a break statement inside the inner loop.
We have used it inside a conditional statement such that if both the numbers are equal to 2,
the inner loop gets terminated.
The flow then moves to the outer loop. Hence, the combination (2, 2) is never printed.
12/11/2024
Fundamentals of R
R break and next
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 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.
12/11/2024
Fundamentals of R
R break and next
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.
12/11/2024
Fundamentals of R
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. You 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:
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.
12/11/2024
Fundamentals of R
R repeat 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.
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.
12/11/2024
Fundamentals of R
R repeat Loop
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,
In the above program, since we have not
included any break statement with an exit
condition, the program prints the sum of
numbers infinitely.
12/11/2024
Fundamentals of R
R repeat Loop
Example 3: repeat Loop with next Statement
You can also use a next statement inside a repeat loop to skip an iteration. For example,
Here, we have a repeat loop where we
break the loop if x is equal to 4. We
skip the iteration where x becomes
equal to 2.
12/11/2024
Fundamentals of R
R 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:
12/11/2024
Fundamentals of R
R Functions
Call the Function
After you have defined the function, you can call the function using the function name and arguments.
For example,
Here, we have called the function with two arguments - 2 and 3. This will print the value of 2 raised to
the power 3 which is 8.
The arguments used in the actual function are called formal arguments. They are also called
parameters. The values passed to the function while calling the function are called actual arguments.
12/11/2024
Fundamentals of R
R Functions
Named Arguments
In the above function call of the power() function, the arguments passed during the function call must
be of the same order as the parameters passed during function declaration.
This means that when we call power(2, 3), the value 2 is assigned to a and 3 is assigned to b. If you
want to change the order of arguments to be passed, you can use named arguments. For example,
Here, the result is the
same irrespective of the
order of arguments that
you pass during the
function call.
12/11/2024
Fundamentals of R
R Functions
You can also use a mix of named and unnamed arguments. For example ,
12/11/2024
Fundamentals of R
R Functions
Default Parameters Values
You can assign default parameter values to functions. To do so, you can specify an appropriate
value to the function parameters during function definition.
When you call a function without an argument, the default value is used. For example,
Here, in the second call
to power() function, we have
only specified the b argument
as a named argument. In such
a case, it uses the default value
for a provided in the function
definition.
12/11/2024
Fundamentals of R
R Functions
Return Values
You can use the return() keyword to return values from a function. For example,
Here, instead of printing the result inside the function, we have returned a^b. When we call
the power() function with arguments, the result is returned which can be printed during the call.
12/11/2024
Fundamentals of R
R Functions
Nested Function
In R, you can create a nested function in 2 different ways. Here, we have created a
By calling a function inside another function call. function called add() to add
By writing a function inside another function. two numbers. But during the
function call, the arguments
Example 1: Call a Function Inside Another Function Call are calls to
Consider the example below to create a function to add two numbers. the add() function.
First, add(1, 2) and add(3,
4) are computed and the
results are passed as
arguments to the
outer add() function. Hence,
the result is the sum of all
four numbers.
12/11/2024
Fundamentals of R
R Functions
Example 2: Write a Function Inside Another Function
Let's create a nested function by writing a function inside another function.
Here, we cannot directly call
the power() function because
the exponent() function is defined
inside the power() function.
Hence, we need to first call the outer
function with the argument a and set it
to a variable. This variable now acts
as a function to which we pass the
next argument b.
12/11/2024