Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

R programming Unit 2

R programming Unit 2
Operators in R: An operator is a symbol that performs some specific operation.
There are 5 different types of operators in r, namely, Arithmetic operators,
Assignment operators, Comparison Operators, Logical and Miscellaneous operators.
Arithmetic Operators: They are used to perform simple arithmetic operations as
described in table below:

Operator Meaning Example Result if a=10 and b=3


+ Addition a+b 13
- Subtraction a-b 7
* Multiplication a*b 30
/ Division a/b 3.3333333
^ Exponentiation a^b 100
%% Modulus a%b 1
%/% Integer Division a%/%b 3

Assignment operators: Assignment operators in R are used to assigning values to


various data objects or variables in R. The objects may be , vectors, or functions.
There are two kinds of assignment operators: Left and Right assignment opeartors
Left Assignment (<-or <<- or =): These operators are used to assign the value of
LHS to the Variable on the RHS.
Examples:
x<-10
z=10
A<<-20
Right hand Assignment(->,->>): These operators are used to assign the RHS to
the Variable on the LHS.
Examples:
10->x
20->>z

GOGTE BCA 1
R programming Unit 2

Comparison Operators: Comparison operators are used to compare two values.


They are also known as relational 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.The various relational operators in R are listed below:

Example: if a=10, b=5 then the relation expression a<b will return FALSE

Logical Operators: Logical operations 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.

GOGTE BCA 2
R programming Unit 2

Example: if a=10, b=20, c=5 and d=2 then the expression (a+b)>30 && (c+d)>5
will return TRUE
Miscellaneous Operators:Miscellaneous operators are used to manipulate data.
The various miscellaneous operators are listed below:

Control Statements: Control statement or Control structures are programming


Statements that can alter the flow of execution in a program. There are two types of
control Statement in R:
1. Branching Control structures: These are decision making statements and are
used to test a condition. Hence, they are also known as conditional statement in R.
There are two important branching control structures, namely, if statement and
switch statement.

GOGTE BCA 3
R programming Unit 2

if statement: The if statement is used to test conditions. There are three forms of if
statement, namely, simple if, if…else and if…else if.
Simple if statement: In simple if the condition is tested first. If it is true then the
statement block following it will be executed.
Syntax:

Example:
if(ch==1){
print(“hello”)
}
if…else statement: In this type of if statement the statement block I is executed
when the condition is true and statement block II is executed when the condition is
false.
Syntax:

GOGTE BCA 4
R programming Unit 2

Example:
if(n>0){
print(“Number is positive”)
}else{
print(“Number is negative”)
}
if…else…if statement: This type of if statement is used to test multiple conditions.
Here, whenever a matching condition is found the corresponding statement block is
executed. However, when none of the conditions match the else body is executed.

Example:
if(n>0){
print(“Number is positive”)
}else if(n<0){
print(“Number is Negative”)
}else{
print(“Given number is a zero”)
}

GOGTE BCA 5
R programming Unit 2

Switch statement: The switch is multiway branching statement. It is generally used


as a substitute for long if statements. It allows a variable to be tested for equality
against a list of values. Whenever a amtch is founf the corresponding statement is
executed
Syntax:

The evaluation of switch statement is done in two ways:


Based on Index
If the cases are values like a character vector, and the expression is evaluated to a
number then the expression's result is used as an index to select the case.
Example:
switch(3, “orange”,”apple”,”berry”,”nuts”)
Output:
“berry”

Based on Matching Value


When the cases have both case value and output value like ["case_1"="value1"],
then the expression value is matched against case values. If there is a match with the
case, the corresponding value is the output.
Example:
val1<- as.integer(readline(prompt="Enter a first number"))
val2 <- as.integer(readline(prompt="Enter a second number"))
cat("1. add 2. sub 3. mul 4. div 5. modulus 6. Power")
ch <- readline(prompt="Enter yourr choice")
switch(
ch,
"1" = cat("Addition =", val1 + val2),

GOGTE BCA 6
R programming Unit 2

"2" = cat("Subtraction =", val1 - val2),


"3" = cat("Multiplication =", val1 * val2),
"4" = cat("Division = ", val1 / val2),
"5" = cat("Modulus =", val1 %% val2),
"6" = cat("Power =", val1 ^ val2)
)

Looping control structures: They are repetitive statements used to repeatedly


execute a block of statements. There are three looping statements in R, namely, for
loop, while loop and repeat loop.
For loop: For loop in R Programming Language 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 and excutes for a
fixed number op times.
Syntax:

Example:
for (val in 1: 5)
{
print(val)
}

While loop: while loop is an entry controlled loop. Here the condition is tested at
the beginning of the loop. If the condition is true then the vbbody of the loop is
executed otherwise the loop is terminated. Hence, while loop used when the exact
number of iterations of a loop is not known before hand.

GOGTE BCA 7
R programming Unit 2

Syntax:

Example:
n=1
while (n <= 5)
{
print(n)
n= n + 1
}

Repeat loop: Repeat loop in R is used to iterate over a block of code multiple
number of times. The keyword used for the repeat loop is 'repeat'. It executes a block
of statement repeated until a break statement is found. Since there is no condition
tested at the beginning or end of the loop, it is necessary to include a conditional
statement within the loop, otherwise it may result in an infinite loop
Syntax:

Example:
n=1
repeat
{
print(n)
n=n+1
GOGTE BCA 8
R programming Unit 2

if(n > 5)
{
break
}
}

Jump statements in Loops: R programming Language provides various keywords


and statements that can be used to jump a loop, namely, break, next and stop.

Break: It is a keyword and is used to terminate the loop at a particular iteration(loop)

Example:
for (val in 1: 5)
{
if (val == 3)
{
# using break keyword
break
}
print(val)
}

Output: 1 2

Next:It is also a keyword and is used to skip a particular iteration in the loop.
Example:
for (val in 1: 5)
{
if (val == 3)
{
next
}
print(val)
}

Output: 1 2 4 5

Stop(): Stop is a function that is used to terminate or exit a program.


GOGTE BCA 9
R programming Unit 2

Example:

for (val in 1: 5)
{
if (val == 3)
{
stop()
}
print(val)
}

Output: 1 2 Program terminates with warning message

Functions in R: A function a subprogram or subroutine that performs some specific


task. It is a block of code that executes only when it is called. Functions are useful
when you want to perform a certain tasks multiple times. It is possible to pass data
objects to a function. These data objects are known as parameters or arguments. A
function can return data as a result.

There are two types of functions:

 Built-in Functions - They are a part of the R programming language Library.


Examples: min(), max(), sum(), mean(), prod() etc

 User-Defined functions- They are defined and created by the user/ Programmer.

Creating Function: A user defined function can be created using the following
Syntax:

funcname<-function(argument list)){
statements
statements
Statements
return(value)
}

Where,
Funcname- is an identifier
GOGTE BCA 10
R programming Unit 2

Argumenet list- It is optional and indictae the data values being passed to the
function
Return-It is used to return a value to the called function

Example:
greet <- function(name) {
cat("Hello World!",name)
}

Calling a Function: It is necessary to call a function using its name in order to


execute it.

Syntax:

funcname(arguments)
Example:
greet(“jhon”)

Function Arguments: Data values passed to a function are known as arguments.


Generally, arguments are passed in the same order as in the function definition.
There is a one-to-one correspondence between actual and formal arguments.
Example:
Rectangle<-function(length=5, breadth=4){
area<-length * breadth
return(area)
}

# normal function call


print(Rectangle(2, 3))

However, in R, the functiona call can contain argument names if parameter order is
not followed.
Example:
Rectangle<-function(length=5, breadth=4){
area<-length * breadth
return(area)
}
#argument names are used because order is changed
print(Rectangle(breadth = 8, length = 4))
GOGTE BCA 11
R programming Unit 2

Default values- Default values can be assigned to parameters in the function


definition. Default values are used to execute the function when no arguments are
passed it.

Example:
Rectangle<-function(length=5, breadth=4){
area<-length * breadth
return(area)
}

# no arguments are passed so default arguments are used


print(Rectangle())

Returning Complex Objects: A function can return complex numbers using the
return statement:

Example:
add<-function(a,b){
c<-a+b
return( c ) #c contains a complex bnumber
}

print(add(2+3i, 3+4i))

Output:
5+7i

Programming Examples:
#Program to check whether a given number is even or odd
cat("Enter a number")
n<-as.integer(readline())

if(n %% 2 == 0){
print("even number")
} else{
print("Odd number")
}

GOGTE BCA 12
R programming Unit 2

# Program to find largest of three numbers

a <- as.integer(readline(prompt="Enter a first number"))


b <- as.integer(readline(prompt="Enter a second number"))
c <- as.integer(readline(prompt="Enter a second number"))

if(a>b && a>c){


cat(a, " is largest")
}else if(b>a && b>c){
cat(b, " is largest")
}else{
cat(c,"is largest")
}

# Program to reverse a number using Function

revnum<-function(n){
rev=0
while(n>0)
{
dig<- n%%10
rev=(rev*10)+dig
n<-n%/%10
}
return(rev)
}

cat("enter a number")
n<-as.numeric(readline())

r= revnum(n)
cat("Reversed number is ",r)
if(r==n){
cat("\n",n,"is a Palindrome number")
}else{
cat("\n",n,"is not a Pailndrome")
}

GOGTE BCA 13
R programming Unit 2

#program to find the factorial of a number

n<-as.integer(readline(prompt="Enter a number: "))


f<- 1

if(n < 0) {
print("Not possible for negative numbers")
} else if(n == 0) {
print("The factorial of 0 is 1")
} else {
for(i in 1:n) {
f=f*i
}
cat("The factorial of", n ,"is",f)
}

# Program Illustrate with for loop and stop on condition, to print the error
message.

sum <- 0
n <- as.numeric(readline("How many elements: "))
for(i in 1:n)
{

ele <- as.numeric(readline("Enter an element: "))


if(ele<0)
{
stop("You have entered negative value. Terminating the program.")
}
sum <- sum + ele
}
cat("Sum of numbers =", sum)

GOGTE BCA 14

You might also like