0% found this document useful (0 votes)
6 views33 pages

R Language Mathematical Operators Guide

The document provides an overview of mathematical operations in R, detailing various types of operators including arithmetic, relational, logical, assignment, and miscellaneous operators. It explains how these operators function with vectors and includes examples for each type. Additionally, it covers decision-making statements and loops in R, outlining their syntax and usage.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views33 pages

R Language Mathematical Operators Guide

The document provides an overview of mathematical operations in R, detailing various types of operators including arithmetic, relational, logical, assignment, and miscellaneous operators. It explains how these operators function with vectors and includes examples for each type. Additionally, it covers decision-making statements and loops in R, outlining their syntax and usage.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT- 3

MATHEMATICAL OPERATIONS
• An operator is a symbol that tells the complier to perform specific mathematical or logical
manipulations.

• R language is rich in built-in operators and provides following types of operators.

Types of Operators

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators

4. Assignment Operators

5. Miscellaneous Operators

Arithmetic Operators

• Arithmetic operations in R simulate various math operations,like addition, subtraction,


multiplication, division and modulo using the specified operator between operands.

• The operators act on each element of the vector.

• A vector is simply a list of items that are of the same type. “c( )”

Operator: + (Addition operator)

• Adds two Vectors.

Example:

> v <- c( 2, 5.5, 6)

> t <- c(8, 3, 4)

> print(v+t)

Output:
[1] 10.0 8.5 10.0

Operator: - (Subtraction operator)

• Subtracts second vector from the first.

Example:

> v <- c( 2, 5.5, 6)

> t <- c(8, 3, 4)

> print(v-t)
Output:
[1] -6.0 2.5 2.0

Operator: * (Multiplication Operator)

• Multiplies both vectors.

Example:

> v <- c( 2, 5, 6)

> t <- c(8, 3, 4)

> print(v*t)

Output:

[1] 16 15 24

Operator: / (Division Operator)

• Divide the first vector with the second.

Example:

> v <- c( 8, 10)

> t <- c(2, 5)

> print(v/t)

Output:

[1] 4 2

Operator: %% (Modulo Operator)

• Give the remainder of the first vector with the second.

Example:

> v <- c( 13, 23)

> t <- c(2, 7)

> print(v%%t)

Output:

[1] 1 2
Operator: %/% (Integral Division Operator)

• Integral Division – Same as Division. But it returns the integer value by flooring the extra decimals.

• The integer division (%/%) rounds the result down to the nearest whole number.

Example:

> v <- c( 12, 23)

> t <- c(2, 7)

> print(v%/%t)

> print(v/t)

Output:

[1] 6 3 #Integral division

[1] 6.000000 3.285714 #Division

Operator: ^ (Exponent)

 The first vector raised to the exponent of second vector.


Example:

> v <- c( 3, 2)

> t <- c(4, 8)

> print(v^t)

Output:

[1] 81 256

Relational Operators

• Each element of the first vector is compared with the corresponding element of the second vector.

• The result ofcomparison is a Boolean value. (TRUE,FALSE)

• A TRUE value is always considered to be greater than FALSE.

Operator: > (Greater than)

• Checks if each element of the first vector is greater than the corresponding element of
the second vector.

Example:

> v <- c(1, 4, 8)

> t <- c(2, 7, 3)

> print(v>t)
Output:

[1] FALSE FALSE TRUE

Operator: < (Less than)

• Checks if each element of the first vector is less than the corresponding element of the second
vector.

Example:

> v <- c(1, 4, 8)

> t <- c(2, 7, 3)

> print(v<t)

Output:

[1] TRUE TRUE FALSE

Operator: == (Equal)

• Checks if each element of the first vector is equal to the corresponding element of the second vector.

Example:

> v <- c(1, 5, 8)

> t <- c(2, 5, 3)

> print(v==t)

Output:

[1] FALSE TRUE FALSE

Operator: <= (Less than or equal to)

• Checks if each element of the first vector is less than or equal to the corresponding element of the
second vector.

Example:

> v <- c(1, 5, 8)

> t <- c(2, 5, 3)

> print(v<=t)

Output:

[1] TRUE TRUE FALSE


Operator: >= (Greater than or equal to)

• Checks if each element of the first vector is greater than or equal to the corresponding element of the
second vector.

Example:

> v <- c(1, 5, 8)

> t <- c(2, 5, 3)

> print(v>=t)

Output:

[1] FALSE TRUE TRUE

Operator: != (Not equal)

• Checks if each element of the first vector is unequal to the corresponding element of the second
vector.

Example:

> v <- c(1, 5, 8)

> t <- c(2, 5, 3)

> print(v!=t)

Output:

[1] TRUE FALSE TRUE

Logical Operators

• Logical operators are used to carry out boolean operations like AND,OR,NOT.

• Each element of the first vector is compared with the corresponding element of the second vector.

• The result of comparison is a Boolean value.

Operator: &

• It is called Element-wise Logical AND operator.

• It combines each element of the first vector with the corresponding element of the second vector and
gives a output TRUE if both the elements are TRUE.

Example:

> v <- c(0, 1, FALSE, 2+3i)

> t<- c(TRUE, 1, FALSE, 2+3i)

> print(v&t)
Output:

[1] FALSE TRUE FALSE TRUE

Operator: |

 It is called Element-wise Logical OR operator.


 It combines each element of the first vector with the corresponding element of the second vector and
gives a output TRUE if one the elements is TRUE.

Example:

> v <- c(0, 1, FALSE, 2+3i)

> t<- c(TRUE, 1, FALSE, 2+3i)

> print(v|t)

Output:

[1] TRUE TRUE FALSE TRUE

Operator: !

• It is called Logical NOT operator.

• This operator takes each element of the vector and gives the opposite logical value.

Example:

> v <- c(0, TRUE, FALSE)

> print(!v)

Output:

[1] TRUE FALSE TRUE

Operator: &&

• Called Logical AND operator.

• This operator takes first element of both the vectors and gives the TRUE only if both are TRUE.

Example:

> v <- c(TRUE, 1, FALSE)

> t <- c(TRUE, 1, TRUE)

> print(v&&t)

Output:

[1] TRUE
Operator: ||

• Called Logical OR operator.

• This operator takes the first element of both the vector and gives the result TRUE, if one of them is
true.

Example:

> v <- c(0,0,TRUE,2+2i)

> t <- c(1,3,TRUE,2+3i)

> print(v||t)

Output:

[1] TRUE

Assignment Operators

• These operators are used to assign values to vectors.

Operator: <- or = or <<-

• Called Left Assignment.

Example:

> v1 <- c("ab", TRUE)

> v2 <<- c(3, 1, 8, 5)

> v3 = c('A', 'B', 'C', 'D')

> print(v1)

> print(v2)

> print(v3)

Output:

[1] "ab" "TRUE"

[1] 3 1 8 5

[1] "A" "B" "C" "D"

Operator: -> or ->>

• Called Right Assignment.

Example:

> c("ab", TRUE) -> v1

> c(3, 1, 8, 5) ->> v2


> print(v1)

> print(v2)

Output:

[1] "ab" "TRUE"

[1] 3 1 8 5

Operator: -> or ->>

• Called Right Assignment.

Example:

> c("ab", TRUE) -> v1

> c(3, 1, 8, 5) ->> v2

> print(v1)

> print(v2)

Output:

[1] "ab" "TRUE"

[1] 3 1 8 5

Miscellaneous Operators

• Miscellaneous operators are used to manipulate data and used to for specific purpose.

Operator: : (Colon)

• Colon operator.

• It creates the series of numbers in sequence for a vector.

Example:

> v <- 2:8

> print(v)

Output:

[1] 2 3 4 5 6 7 8

Operator: %in%

• This operator is used to identify if an element belongs to a vector.

• If it exists, print the output as TRUE.


Example:

> v1 <- 4

> v2 <- 9

> t <- c(1, 2, 3, 4, 5)

> print(v1 %in% t)

> print(v2 %in% t)

Output:

[1] TRUE

[1] FALSE

Operator: %*%

• This operator is used to multiply a matrix with its transpose.

Example:

> a = matrix( c(1, 2, 3, 4), nrow=2, ncol=2)

> t = a %*% t(a)

> print(a)

> print(t(a))

> print(t)

Output:

[,1] [,2]

[1,] 1 3

[2,] 2 4

[,1] [,2]

[1,] 1 2

[2,] 3 4

[,1] [,2]

[1,] 10 14

[2,] 14 20
Precedence and Associativity of R Operators

• When an expression includes multiple operators then each of the single part of given expression is
evaluated in a certain order following some rules defined as per operator precedence.

• Operator with higher precedence is evaluated first and operator with lowest precedence is evaluated
at last.

• Operators can either follow left-associative, right-associative or have no associativity.

Operator Precedence in R (Highest to Lowest)

Examples:

> v<- 20 + 3 * 8

> print(v)

Output:

[1] 44

> s<- 20 / 4 / 6

> print(s)

Output:

[1] 0.83333

 The order of the operations can be changed by using round parenthesis ( ).

> v1<- ( 20 + 3 ) * 8

> print(v1)

Output:

[1] 184
> v2<- 4 ^ 3 ^ 2

> print(v2)

Output:

[1] 262144

> v<- (2 ^ 2) ^ 3

> print(v)

Output:

[1] 64

When there are more than one exponent operators (^) in an expression, R will evaluate the exponent (^)
from right to left.

Concatenate two or more vectors in R

 This is a function that combines its arguments.


 This method combines the arguments and results in a vector.
Syntax:

c(argument, argument,..)

Arguments : The objects to be concatenated

Example:

> vec1 <- 1:4

vec1

>vec2 <- 4:1

vec2

c(vec1,vec2)

Output:

[1] 1 2 3 4

[1] 4 3 2 1

[1] 1 2 3 4 4 3 2 1

Example:

> x <- c (10 , 20 , 30)

> y <- c (40 , 50 , 60)

> z <- c ( x , y)

print (z)
Output:

[1] 10 20 30 40 50 60

DECISION MAKING
• Decision making statements helps to decide whether to execute a block of code or not, based on
condition.

• Decision making statements are also called conditional statements.

Types of statements:

• if statement

• if …else statement

• switch statement

R –if Statement

• If statement consists of a Boolean expression followed by one or more statements.

• If the expression is true, the statement gets executed , if the expression is false nothing happens.

Syntax:

if(boolean_expression) {

// statement(s) will execute if the boolean expression is true.

Flow chart:
Example:

a <- 5

if(a > 0)

print("Positive Number")

Output:

[1] "Positive Number"

R –If…Else Statement

• If statement can be followed by an optional else statement which executes when the boolean
expression is false.

Syntax:

if(boolean_expression) {

// statement(s) will execute if the boolean expression is true.

} else {

// statement(s) will execute if the boolean expression is false.

Flow chart:

Example:
Bag <- c(“Apple”, ”Cake” , “Chips”, “Bottle”)

Item1 <- “apple”

Item2 <- “Cake”

if(Item1 %in% Bag)

print(“First item is in Bag.”)

else

print(“First item is not in Bag.”)

Output:

[1] “First item is not in Bag.”

The if…else if…else Statement

 An if statement can be followed by an optional else if…else statement, which is very useful to
test various conditions using single if…else if statement.
 When using if, else if, else statements there are few points to keep in mind.
 The else statement must come after any else if statement.
 if statements can have many else if statements.
 The else if statements come before the else statements.
 Once an else if succeeds, none of the remaining else if’s or else’s will be tested.

Syntax:

If(boolean_expression 1) {

// Executes when the boolean expression 1 is true.

}else if( boolean_expression 2) {

// Executes when the boolean expression 2 is true.

}else if( boolean_expression 3) {

// Executes when the boolean expression 3 is true.

}else {

// executes when none of the above condition is true.

}
Flow chart:

Example:

x <- c(“what”,”is”,”truth”)

if(“Truth” %in% x){

print(“Truth is found the first time”)

} else if (“truth” %in% x) {

print(“truth is found the second time”)

}else{
print(“No truth found”)

Output:

[1] “truth is found the second time”

R –Switch Statement

• A switch statement allows a variable to be tested for equality against a list of values.

• Each value is called a case, and the variable being switched on is checked for each case.

Syntax:

Switch(expression, case1, case2, case3….)

Rules apply to a switch statement:


• If the value of expression is not a character string it is coerced to integer.

• programmer can have any number of case statements within a switch.

• For character string as a condition for switch statement, the string is matched to the available cases.

• If there is more than one match, the first matching element is returned.

• No Default argument is available.

Flow chart:

Example:

a=2

b=1

x= switch(

a+b,

“John”,

“Harish”

“Vipin”,

“Ishan”

Print(x)

Output:
[1] “Vipin”

Loops
• In R programming, require a control structure to run a block of code multiple times.

• 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.

• There are two components of a loop

1. control statement loop

2. Loop body

• The control statement controls the execution of statements depending on the condition

• Loop body consists of the set of statements to be executed.

Types of loops:

1. For Loop

2. While Loop

3. Repeat Loop

4. Nested Loop

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.

• For loop is commonly used to iterate over items of a sequence.

• 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(value in sequence)

statement

Flow diagram:
Example:

V <- c(1:4)

for(I in V)

Print(i)

Output:

[1] 1

[1] 2

[1] 3

[1] 4

Nested Loop

• A nested for-loop has a for-loop inside of another for-loop.

• For each of iteration in the outer for-loop, the inner loop will be executed unless a final condition is
met for the inner loop.

• Once an inner for-loop is executed for a particular outer iteration, the outer for-loop goes for the next
iteration, and the inner loop will be executed for this iteration.

• This process repeats itself till the final condition is met for the outer for-loop.

Syntax:

for(element1 in sequence)
{

for(element2 in sequence)

//body

Example:

for(number1 in 1:3)
{
for(number2 in 1:3)
{
print(paste(number1, “+”, number2, “=”number1 + number2));
}
}

Output:

[1] “1 + 1 = 2”
[1] “1 + 2 = 3”
[1] “1 + 3 = 4”
[1] “2 + 1 = 3”
[1] “2 + 2 = 4”
[1] “2 + 3 = 5”
[1] “3 + 1 = 4”
[1] “3 + 2 = 5”
[1] “3 + 3 = 6”

While loop in R

• It is a type of control statement which will run a statement or a set of statements repeatedly unless
the given condition becomes false.

• It is also 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:

while(condition)

statement

Flow diagram:
Example:

n <-5

factorial <-1

i<-1

while (i<=n)

factorial=factorial*i

i=i+1

print(factorial)

Output:

[1] 120

Repeat Loop in R

• It is a simple loop that will run the same statement or a group of statements repeatedly until the stop
condition has been encountered.

• Repeat loop does not have any condition to terminate the loop, a programmer must specifically place
a condition within the loop’s body and use the declaration of a break statement to terminate this loop.

• If no condition is present in the body of the repeat loop then it will iterate infinitely.

Syntax:

repeat

statement

if(condition)

{
break

Flow diagram:

Example:

val = 1

repeat

print(val)

val = val + 1

if(val > 5)

break

Output:

[1] 1

[2] 2

[3] 3

[4] 4

[5] 5

Jump Statements in Loop


• The jump statements are used in loops to terminate the loop at a particular iteration or to skip a
particular iteration in the loop.

• The two most commonly used jump statements in loops are:

1. Break statement

2. Next statement

Break Statement

• The break keyword is a jump statement that is used to terminate the

loop at a particular iteration.

Syntax:

break

Example:

for(val in 1:5)

if(val==3)

break

print(val)

Output:

[1] 1

[2] 2

Next Statement

• The next keyword is a jump statement which is used to skip a particular iteration In the loop.

Syntax:

next

Example:

for(val in 1:5)

if(val==3)
{

next

print(val)

Output:

[1] 1

[1] 2

[1] 4

[1] 5

FUNCTIONS
• A function is a block of organized, reusable code that performs a specific task.

• Functions are designed to take some input (arguments or parameters), process it, and then return a result.

• R comes with a wide range of built-in functions that perform tasks.

• User can create their own functions to perform specific tasks.

Function Definition:

 R function is created by using the keyword function.

Syntax:

function_name &lt;- function(arg_1, arg_2, …)

Function body

Function Components:

• Function Name − This is the actual name of the function. It is stored in R environment as an object with
this

name.

• Arguments −When a function is invoked, user pass a value to the argument. Arguments are optional; that
is,a function may contain no arguments. Also arguments can have default values.

• Function Body − The function body contains a collection of statements that defines what the
function does.

• Return Value − The return value of a function is the last expression in the function body to be evaluated.
Types of Function:

•Built-in Function

• user-defined function

Built-in Function

• The functions which are already created or defined in the programming framework are known as built-in

functions.

• R have different types of built-in functions such as seq(), mean(), print(),min(),c(),max(), and sum(x) etc.

• print() - Used to print the specified object or objects.

• seq() - Generates sequences of numbers.

• mean() - Calculates the mean (average) of a numeric vector.

• sum() - Calculates the sum of a numeric vector.

• c() - Concatenates or combines values into a vector.

mean() and c():

Example:

numbers &lt;- c(2, 4, 6, 8, 10)

mean_value &lt;- mean(numbers)

print(mean_value)

Output:

[1] 6

Example:

# Creating sequence of numbers from 10 to 30.

print(seq(10,30))

# Finding the sum of numbers from 20 to 40.

print(sum(20:40))

Output:

[1] 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

[1] 630

Built-in Math Functions


• R also has many built-in math functions that allows user to perform mathematical tasks on numbers.

• For example, the min() and max() functions can be used to find the lowest or highest number in a set:

Example:

max(23, 43, 16)

min(69, 33, 67)

Output:

[1]43

[1]33

sqrt()

 The sqrt() function returns the square root of a number.

Example:

sqrt(9)

Output:

[1] 3

abs()

The abs() function returns the absolute (positive) value of a number:

Example:

abs(-8.9)

Output:

[1] 8.9

ceiling() and floor()

• The ceiling() function rounds a number upwards to its nearest integer.

• The floor() function rounds a number downwards to its nearest integer, and returns the result.

Example:

ceiling(1.7)

ceiling(1.3)

Output:
[1]2

[1]2

Example:

floor(1.9)

floor(1.4)

Output:

[1]1

[1]1

User-defined Function

• R allows user to create their own function in their program.

• A user defines a user-define function to fulfill the requirement of user.

• Once these functions are created, User can use these functions like in-built function.

Example:

multiply <- function(x){

result <- x * 10

print(result)

x <- 385

multiply(x)

Output:

[1] 3850

Call a Function

• To call a function, use the function name followed by parenthesis, like my_function():

Example:

my_function <- function()

print("Hello World!")
}
my_function() # call the function named my_function

Output:

[1] “Hello World!”


Arguments

• Information can be passed into functions as arguments.

• Arguments are specified after the function name, inside the parentheses.

• Add as many arguments , just separate them with a comma.

Example:

my_function <- function(fname)

paste(fname,"Williams")

my_function("Emily")

my_function("Elisa")

my_function("Lily")

Output:

[1] "Emily Williams"

[1] "Elisa Williams"

[1] "Lily Williams"

Example for number of arguments:

my_function <-function(fname,lname)

{
paste(fname,lname)
}

my_function("Peter",”Williams”)

Output:

[1] "Peter Williams"

Calling a Function with Default Argument


• To get the default result, User assign the value to the arguments in the function definition, and then
user call the function without supplying argument.

• If user pass any argument in the function call, then it will get replaced with the default value of the
argument in the function definition.

Example:

my_function<-function( dept="CS”)

paste("Department=", dept)

my_function("BCA")

my_function("IT")

my_function()

my_function("CT")

Output:

[1] "Department= BCA"

[1] "Department= IT"

[1] "Department= CS"

[1] "Department= CT"

Return Values

• To let a function return a result, use the return() function.

Example:

my_function<-function(x){
return(x*x)
}
print(my_function(10))
print(my_function(20))
print(my_function(40))

Output:

[1] 100

[1] 400

[1] 1600

STRING
• Strings are a bunch of character variables.

• Any value coded within a pair of single quote (' ') and double quotes (" ") in R programming is
termed as a 'string'.

• Internally R stores every string within double quotes, even when user create them with single quote.

Example:

message1<-‘Rprogramming’
print(message1)
message2<-“Helloworld!”
print(message2)

Output:

[1]“Rprogramming”
[1] “Hello world!”

String Operations in R

• R provides various built-in functions that allows to perform different operations on strings.

• Some of the commonly used string functions are,

[Link] the length of a string

[Link] two strings

[Link] two strings

[Link] the string case

1. Find Length of R String

• The nchar() method to find the length of a string.

Example:

message1 <- "hello world"

nchar(message1)

Output:

[1] 11

• Here, nchar() returns the number of characters present inside the string.

2. Join Strings Together

• The paste() function to join two or more strings together.

Example:
message1<-“Rprogramming”
message2<-“language”
paste(message1, message2)

Output:

[1] “Rprogramming language”

• Here, the paste() function used to join two strings: message1 and message2.

3. Compare Two Strings in R Programming

• The == operator to compare two strings.

• If two strings are equal, the operator returns TRUE.

• Otherwise, it returns FALSE.

Example:
greeting1 <- "Hello, World!"

greeting2 <- “Hello, Program!"

greeting3 <- "Hello, World!"

print(greeting1 == greeting2)

Output:

[1] False

[1] True

• In the above example,

• greeting1 == greeting2 - returns FALSE because two strings are not equal.

• greeting1 == greeting3 - returns TRUE because both strings are equal.

4. Change Case of R String

• In R, change the case of a string using

• toupper() - convert string to uppercase

• tolower() - convert string to lowercase

Example:

programming_language <- “R Programming"

language_upper <- toupper(programming_language)

cat("Uppercase=", language_upper)

language_lower <- tolower(programming_language)

cat("\nLowercase=", language_lower)
Output:

Uppercase= R PROGRAMMING

Lowercase= r programming

Formatting numbers & strings:

• Numbers and strings can be formatted to a specific style using format() function.

Syntax:

The basic syntax for format function is −

format(x, digits, nsmall, scientific, width, justify = c("left", "right", "centre", "none"))

Following is the description of the parameters used

• x is the vector input.

• digits is the total number of digits displayed.

• nsmall is the minimum number of digits to the right of the decimal point.

• scientific is set to TRUE to display scientific notation.

• width indicates the minimum width to be displayed by padding blanks in the beginning.

• justify is the display of the string to left, right or center.

Example:

result<-format(23.123456789,digits=9)
print(result)

Output:

[1] "23.1234568"

result<-format(c(6,13.14521),scientific=TRUE)
print(result)

Output:

[1] "6.000000e+00" "1.314521e+01"

result<-format(23.47,nsmall=5)
print(result)

Output:

[1] "23.47000"
result<-format(13.7,width=6)
print(result)

Output:

[1] “ 13.7”

result<-format("Hello",width=8,justify="l")
print(result)

Output:

[1] “Hello “

result<-format("Hello",width=8,justify="c")
print(result)

Output:

[1] “ Hello “

Extracting parts of a string

• This function extracts parts of a String using substring() function.

Syntax:

substring(x,first,last)

• x is the character vector input.

• first is the position of the first character to be extracted.

• last is the position of the last character to be extracted.

Example:

result <- substring("program", 4, 5)

print(result)

Output:

[1] “gr”

Check a String

• Use the grepl() function to check if a character or a sequence of characters are present in a string:
Example

str <- "Hello World!“

grepl("H",str)
grepl(“program", str)

output

[1]TRUE

[1]FALSE

You might also like