Unit 4 Ids Notes
Unit 4 Ids Notes
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Miscellaneous Operators
R Arithmetic Operators
These operators are used to carry out mathematical operations like addition
and multiplication. Here is a list of arithmetic operators available in R.
Arithmetic Operators in R
Operator Description
+ Addition
– Subtraction
* Multiplication
/ Division
^ Exponent
# R program to illustrate
Output:
Addition of vectors : 2 5
Subtraction of vectors : -2 -1
Multiplication of vectors : 0 6
Power operator : 0 8
Logical Operators
Relational Operators
R Relational Operators
Relational Operators in R
Operator Description
== Equal to
!= Not equal to
EX:
> x <- 5
> y <- 16
> x<y
[1] TRUE
> x>y
[1] FALSE
> x<=5
[1] TRUE
> y>=20
[1] FALSE
> y == 16
[1] TRUE
> x != 5
[1] FALSE
Operation on Vectors
> x+y
[1] 8 12 4
> x>y
R will issue a warning if the length of the longer vector is not an integral
multiple of the shorter vector.
[1] 11 5 17 7
[1] 1 0 7 2
> x+c(1,2,3)
[1] 3 3 11 4
Warning message:
In x + c(1, 2, 3) :
R Logical Operators
Logical Operators in R
Operator Description
! Logical NOT
| Element-wise logical OR
|| Logical OR
But && and || examines only the first element of the operands resulting into a
single length logical vector.
> !x
> x&y
> x&&y
[1] FALSE
> x|y
> x||y
[1] TRUE
R Assignment Operators
Assignment Operators in R
Operator Description
> x <- 5
>x
[1] 5
>x=9
>x
[1] 9
> 10 -> x
>x
[1] 10
Conditional Statements
1. if Statement
1. if(boolean_expression) {
2. // If the boolean expression is true, then statement(s) will be exe
cuted.
3. }
Flow Chart
EX:1
1. x <-24L
2. if(is.integer(x))
3. {
4. print("x is an Integer")
5. }
Output
EX:2
x <- 100
Output:
2.If-else statement
1. if(boolean_expression) {
2. // statement(s) will be executed if the boolean expression is true.
3. } else {
4. // statement(s) will be executed if the boolean expression is false.
5. }
Flow Chart
Example 1
}else{
Output:
[1] "5 is less than 10"
3. else if statement
1. if(boolean_expression 1) {
2. // This block executes when the boolean expression 1 is true.
3. } else if( boolean_expression 2) {
4. // This block executes when the boolean expression 2 is true.
5. } else if( boolean_expression 3) {
6. // This block executes when the boolean expression 3 is true.
7. } else {
8. // This block executes when none of the above condition is true.
}
Flow Chart
Example 1
marks<-83;
if(marks>75){
print("First class")
}else if(marks>65){
print("Second class")
}else if(marks>55){
print("Third class")
}else{
print("Fail")
Output
EX:2
quantity <- 10
if (quantity <20) {
print('Average day')
} else {
Output
[1] "Not enough for today"
Ex: 3
We can write a chain to apply the correct VAT rate to the product a
customer bought.
price <- 10
if (category =='A'){
} else {
Output
A vat rate of 8% is applied. The total price is 10.8
Iterative Programming in R
In R programming, we require a control structure to run a
block of code multiple times.
Loops come in the class of the most fundamental and strong
programming concepts.
A loop is a control statement that allows multiple executions
of a statement or a set of statements.
The word ‘looping’ means cycling or iterating.
For Loop
While Loop
Repeat Loop
1. For Loop in R
It is a type of control statement that enables one to easily
construct a loop that has to run statements or a set of
statements multiple times.
# R program to illustrate
# application of for loop
# assigning strings to the vector
week < - c('Sunday', 'Monday', Tuesday',
'Wednesday', 'Thursday',
'Friday', 'Saturday')
# using for loop to iterate
# over each string in the vector
for (day in week)
{
# displaying each string in the vector
print(day)
}
Output:
1] "Sunday"
[1] "Monday"
[1] "Tuesday"
[1] "Wednesday"
[1] "Thusrday"
[1] "Friday"
[1] "Saturday"
2.repeat statement
The repeat statement executes the body of the loop until a
break occurs. Be careful while using it because of the infinite
nature of the loop.
We must use the break statement to terminate the loop. The
syntax of the repeat loop is :
1. repeat {
2. commands
3. if(condition) {
4. break
5. }
6. }
Flowchart
Example 1:
1. v <- c("Hello","repeat","loop")
2. cnt <- 2
3. repeat {
4. print(v)
5. cnt <- cnt+1
6. if(cnt > 4) {
7. break
8. }
9. }
Output
3.While Loop
It is a type of control statement which will run a statement or
a set of statements repeatedly unless the given condition
becomes false.
while ( condition )
{
statement
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
# R program to illustrate
n <- 5
factorial <- 1
i <- 1
while (i <= n)
factorial = factorial * i
i=i+1
print(factorial)
Output:
[1] 120
Here, at first, the variable n is assigned to 5 whose factorial is
going to be calculated, then variable i and factorial are
assigned to 1. i will be used for iterating over the loop, and
factorial will be used for calculating the factorial.
In each iteration of the loop, the condition is checked i.e. i
should be less than or equal to 5, and after that factorial is
multiplied with the value of i, then i is incremented.
When i becomes 5, the loop is terminated and the factorial of
5 i.e. 120 is displayed beyond the scope of the loop.
# R program to illustrate
for (val in 1: 5)
# checking condition
if (val == 3)
break
print(val)
Output:
[1] 1
[1] 2
In the above program, if the value of val becomes 3 then the break
statement will be executed and the loop will terminate.
# R program to illustrate
for (val in 1: 5)
# checking condition
if (val == 3)
next
print(val)
Output:
[1] 1
[1] 2
[1] 4
[1] 5
In the above program, if the value of Val becomes 3 then
the next statement will be executed hence the current
iteration of the loop will be skipped. So 3 is not displayed in
the output.
# loop version 1
for (p in primes_list) {
print(p)
}
# loop version 2
for (i in 1:length(primes_list)) {
print(primes_list[[i]])
}
Notice that you need double square brackets - [[ ]] - to select the list
elements in loop version 2.
Output
[1] 2
[1] 3
[1] 5
[1] 7
[1] 11
[1] 13
[1] 2
[1] 3
[1] 5
[1] 7
[1] 11
[1] 13
Functions in R Programming
Components of Functions
Function Name
Arguments
Function Body
Return value
Function Types
Built-in function
Output
[1] 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
[1] 51
[1] 1665
EX: 2
Output:
Math functions
Operator Description
Operator Description
mean(x) Mean of x
median(x) Median of x
var(x) Variance of x
EX: 1
speed <- dt$speed
speed
# Mean speed of cars dataset
mean(speed)
User-defined function
Call a Function
Example
{
print("Hello World!")
}
O/P:
Arguments
Example
{
paste(fname, "Griffin")
}
my_function("Peter")
my_function("Lois")
my_function("Stewie")
O/P;
Return Values
Example
my_function <- function(x) {
return (5 * x)
}
print(my_function(3))
print(my_function(5))
print(my_function(9))
[1] 15
[1] 25
[1] 45
EX:
if(x %% 2 == 0)
return("even")
else
return("odd")
print(evenOdd(4))
print(evenOdd(3))
Output:
[1] "even"
[1] "odd"
# area of a circle
areaOfCircle = function(radius){
area = pi*radius^2
return(area)
print(areaOfCircle(2))
Output:
12.56637
Nested Functions
Code explanation
Line 2: We creatd a function with two parameter
values, x and y.
Code explanation
Line 2: We create an outer function, outerFunction, and pass
a parameter value x to the function.
Line 4: We create an inner function, innerFunction, and pass
a parameter value y to the function.
Line 6: We pass a command to the inner function, which
tells x to multiply y and assign the output to a variable a.
Line 7: We return the value of a.
Line 9: We return the innerFunction.
Line 12: To call the outer function, we create a
variable output and give it a value of 3.
Line 13: We print the output with the desired value of 5 as
the value of the y parameter.
Scopes
f <- function(a, b) {
2 (a * b) / z
3}
a <- 3.14
x*y/a
add(10,11)
1[1] 35.03185
Math Functions
input x. Output
[1] 4
input x. Output
[1] 2
x.
x.
input x. Output
[1] 1 2 8
Output
print(tan(x))
Output
[1] -06536436
[2] -0.7568025
[3] 1.157821
natural print(log(x))
logarithm of Output
common print(log10(x))
logarithm of Output
exponent. print(exp(x))
Output
[1] 54.59815
if(x==0 || x==1)
return(1)
else
return(x*rec_fac(x-1))
Output:
[1] 120
This process continues until the first function call returns its
output, giving us the final result.
Packages in R
Packages in R Programming language are a set of R
functions, compiled code, and sample data.
These are stored under a directory called “library” within the
R environment. By default, R installs a group of packages
during installation.
Once we start the R console, only the default packages are
available by default.
Other packages that are already installed need to be loaded
explicitly to be utilized by the R program that’s getting to use
them.
What are Repositories?
A repository is a place where packages are located and stored
so you can install packages from it.
Organizations and Developers have a local repository,
typically they are online and accessible to everyone.
Some of the most popular repositories for R packages are:
libPaths()
1. install.packages("Package Name")
install.packages("XML")
Output
https://cran.r-
project.org/web/packages/available_packages_by_name.html
1. install.packages("C:\Users\ajeet\OneDrive\Desktop\graphics\xml
2_1.2.2.zip", repos = NULL, type = "source")
1. install.packages("C:\Users\ajeet\OneDrive\Desktop\graphics\xml
2_1.2.2.zip", repos = NULL, type = "source")