0% found this document useful (0 votes)
38 views16 pages

R Module-2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 16

MODULE II

MODULE 2

R PROGRAMMING STRUCTURES

R Programming Structures:
R programming offers various control structures and programming constructs to help you
manage the flow of your code, make decisions, and repeat tasks. These structures are
essential for writing efficient and structured R code. Here are the primary programming
structures in R:

1. Sequential Execution:
 R executes statements sequentially, one after the other, by default. This is the basic
flow of any R script or program.
x <- 5
y <- x + 3
2. Conditional Statements (if-else):
 Conditional statements allow you to execute different code blocks based on specified
conditions. The if statement is used for single conditions, while if-else is used for
branching between two or more conditions.
if (x > 0) {
print("x is positive")
} else {
print("x is non-positive")
}
") }
3. Switch Statements (switch):
 The switch function allows you to select one of several code blocks to execute based
on the value of an expression.
fruit <- "apple"
switch(
fruit,
"apple" = print("It's an apple."),
"banana" = print("It's a banana."),
print("It's something else.")
)
4. Loops:
Loops are used for repetitive tasks. R supports several types of loops, including for,
while, and repeat loops.
 For Loop:
for (i in 1:5) {
print(i)
}
(i) }
 While Loop:
i <- 1
while (i <= 5) {
print(i)
i <- i + 1

R PROGRAMMING PREPARED BY:ARPITA JAIN MCA(II YEAR)


MODULE II

}
( Repeat Loop:
i <- 1
repeat {
print(i)
i <- i + 1
if (i > 5) break
}

5. Control Statements (break and next):


for (i in 1:10) {
if (i == 5) break
if (i %% 2 == 0) next
print(i)
}
 break is used to exit a loop prematurely, and next is used to skip the current iteration
and continue to the next iteration.

(i) }
6. Function Definitions (functions):
my_function <- function(x, y) {
result <- x + y
return(result)
}
 Functions allow you to define reusable blocks of code. You can create your own
functions or use built-in functions in R.
my_function) }
7. Error Handling (try-catch):
 The tryCatch function allows you to handle errors gracefully by specifying what to
do in case of an error. This is important for robust and error-tolerant code.
 result <- tryCatch({
 # Code that might throw an error
 }, error = function(e) {
 # Code to handle the error
 print(paste("An error occurred:", e))
 return(NA)
 })
})
8. Apply Family Functions:
matrix_data <- matrix(1:12, nrow = 3)
result <- apply(matrix_data, MARGIN = 2, FUN = sum)

R provides a set of functions like apply, lapply, sapply, and mapply for applying a function
to elements of data structures like matrices, lists, and data frame

Control Statements in R

R PROGRAMMING PREPARED BY:ARPITA JAIN MCA(II YEAR)


MODULE II

Control statements are expressions used to control the execution and flow of the program
based on the conditions provided in the statements. These structures are used to make a
decision after assessing the variable. In this article, we’ll discuss all the control statements
with the examples.
In R programming, there are 8 types of control statements as follows:
 if condition
 if-else condition
 for loop
 nested loops
 while loop
 repeat and break statement
 return statement
 next statement
if condition
This control structure checks the expression provided in parenthesis is true or not. If true,
the execution of the statements in braces {} continues.
Syntax:
if(expression){
statements
....
....
}
Example:
x <- 100

if(x > 10){


print(paste(x, "is greater than 10"))
}

Output:
[1] "100 is greater than 10"
if-else condition
It is similar to if condition but when the test expression in if condition fails, then statements
in else condition are executed.
Syntax:
if(expression){
statements
....
....
}
else{

R PROGRAMMING PREPARED BY:ARPITA JAIN MCA(II YEAR)


MODULE II

statements
....
....
}
Example:
x <- 5

# Check value is less than or greater than 10


if(x > 10){
print(paste(x, "is greater than 10"))
}else{
print(paste(x, "is less than 10"))
}

Output:
[1] "5 is less than 10"
for loop
It is a type of loop or sequence of statements executed repeatedly until exit condition is
reached.
Syntax:
for(value in vector){
statements
....
....
}
Example:

x <- letters[4:10]

for(i in x){

print(i)

Output:
[1] "d"
[1] "e"
[1] "f"
[1] "g"
[1] "h"
[1] "i"

R PROGRAMMING PREPARED BY:ARPITA JAIN MCA(II YEAR)


MODULE II

[1] "j"

Nested loops
Nested loops are similar to simple loops. Nested means loops inside loop. Moreover, nested
loops are used to manipulate the matrix.
Example:
# Defining matrix
m <- matrix(2:15, 2)

for (r in seq(nrow(m))) {
for (c in seq(ncol(m))) {
print(m[r, c])
}
}

Output:
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10
[1] 12
[1] 14
[1] 3
[1] 5
[1] 7
[1] 9
[1] 11
[1] 13
[1] 15
while loop
while loop is another kind of loop iterated until a condition is satisfied. The testing
expression is checked first before executing the body of loop.
Syntax:
while(expression){
statement
....
....

R PROGRAMMING PREPARED BY:ARPITA JAIN MCA(II YEAR)


MODULE II

}
Example:

x=1

# Print 1 to 5
while(x <= 5){
print(x)
x=x+1
}

Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
repeat loop and break statement
repeat is a loop which can be iterated many number of times but there is no exit condition
to come out from the loop. So, break statement is used to exit from the
loop. break statement can be used in any type of loop to exit from the loop.
Syntax:
repeat {
statements
....
....
if(expression) {
break
}
}
Example:
x=1

# Print 1 to 5
repeat{
print(x)
x=x+1
if(x > 5){
break

R PROGRAMMING PREPARED BY:ARPITA JAIN MCA(II YEAR)


MODULE II

}
}

Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
return statement
return statement is used to return the result of an executed function and returns control to
the calling function.
Syntax:
return(expression)
Example:
# Checks value is either positive, negative or zero
func <- function(x){
if(x > 0){
return("Positive")
}else if(x < 0){
return("Negative")
}else{
return("Zero")
}
}

func(1)
func(0)
func(-1)

Output:
[1] "Positive"
[1] "Zero"
[1] "Negative"
next statement
next statement is used to skip the current iteration without executing the further statements
and continues the next iteration cycle without terminating the loop.
Example:
# Defining vector
x <- 1:10

R PROGRAMMING PREPARED BY:ARPITA JAIN MCA(II YEAR)


MODULE II

# Print even numbers


for(i in x){
if(i%%2 != 0){
next #Jumps to next loop
}
print(i)
}

Output:
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10

Example: Check Leap Year

# Program to check if the input year is a leap year or not

year = as.integer(readline(prompt="Enter a year: "))


if((year %% 4) == 0) {
if((year %% 100) == 0) {
if((year %% 400) == 0) {
print(paste(year,"is a leap year"))
} else {
print(paste(year,"is not a leap year"))
}
} else {
print(paste(year,"is a leap year"))
}
} else {
print(paste(year,"is not a leap year"))
}

Example: Find the factorial of a number

# take input from the user


num = as.integer(readline(prompt="Enter a number: "))
factorial = 1
# check is the number is negative, positive or zero
if(num < 0) {
print("Sorry, factorial does not exist for negative numbers")
} else if(num == 0) {
print("The factorial of 0 is 1")

R PROGRAMMING PREPARED BY:ARPITA JAIN MCA(II YEAR)


MODULE II

} else {
for(i in 1:num) {
factorial = factorial * i
}
print(paste("The factorial of", num ,"is",factorial))
}

Sum of digits

 n<-readline(prompt="please enter any integer value: ")


 please enter any integer value: 12367906.
 n <- as.integer(n)
 sum<-0.
 while(n!=0){
 sumsum=sum+(n%%10)
 n=as.integer(n/10)
 }

Example: How to check a number is a palindrome or not in R

R PROGRAMMING PREPARED BY:ARPITA JAIN MCA(II YEAR)


n = as.integer(readline(prompt = "Enter a number :"))
MODULE II
rev = 0
num = n

while (n > 0) {
r = n %% 10
rev = rev * 10 + r
n = n %/% 10
}

if (rev == num)
{
print(paste("Number is palindrome :", rev))
}
else{
print(paste("Number is not palindrome :", rev))
}

Example: Check Prime Number

# Program to check if the input number is prime or not

# take input from the user


num = as.integer(readline(prompt="Enter a number: "))

flag = 0
# prime numbers are greater than 1
if(num > 1) {
# check for factors
flag = 1
for(i in 2:(num-1)) {
if ((num %% i) == 0) {
flag = 0
break
}
}
}

if(num == 2) flag = 1
if(flag == 1) {
print(paste(num,"is a prime number"))
} else {
print(paste(num,"is not a prime number"))
}
R PROGRAMMING PREPARED BY:ARPITA JAIN MCA(II YEAR)
Looping over Objects in R Programming
MODULE II

Simplicity and Safety: R is designed to be an accessible language for statisticians, data


scientists, and researchers who may not have a strong background in computer science.
Eliminating pointers simplifies the language and reduces the risk of memory-related bugs,
such as segmentation faults or memory leaks.

1. Garbage Collection: R uses automatic garbage collection to manage memory, so users don't
need to worry about deallocating memory explicitly. This approach is more user-friendly and
helps prevent memory leaks.
2. High-Level Abstractions: R provides high-level data structures like vectors, lists, data
frames, and factors, which are designed to simplify data manipulation. These structures
abstract away the low-level memory details.
3. Focus on Data Analysis: R's primary purpose is data analysis and statistical computing. By
abstracting memory management, R allows users to concentrate on data-related tasks rather
than managing memory.

While R doesn't have pointers in the traditional sense, it does provide a powerful and flexible
system for working with data through its data structures and functions. If you need to interact
with low-level memory, interface with other languages like C or C++ is possible through R
packages like "Rcpp," which allows you to write and call C/C++ code from within R while
still benefiting from R's high-level features and memory management.

Recursion in R
Recursion is a programming technique in which a function calls itself to solve a problem. In
R, you can create recursive functions just like in many other programming languages. Here's
a basic example of a recursive function in R:

# Recursive function to calculate the factorial of a number

factorial <- function(n) {

if (n == 0 || n == 1) {

return(1)

} else {

return(n * factorial(n - 1))

# Calculate the factorial of 5

result <- factorial(5)

print(result) # Output: 120

R PROGRAMMING PREPARED BY:ARPITA JAIN MCA(II YEAR)


MODULE II

In this example, the factorial function calculates the factorial of a number n using recursion.
It checks for the base cases where n is 0 or 1 (the factorial of 0 and 1 is 1), and in other cases,
it recursively calls itself with n-1 until it reaches the base cases.

Here's how recursion works in this example:

 factorial(5) calls factorial(4) since 5 * factorial(4) is required.


 factorial(4) calls factorial(3) since 4 * factorial(3) is required.
 This pattern continues until factorial(1) is reached, which returns 1.

Then, the results are propagated back up the call stack to calculate the final result, which is
120.

When writing recursive functions in R, it's important to define one or more base cases where
the recursion stops. Without base cases, the function will keep calling itself indefinitely,
leading to a stack overflow error.

Here are some best practices for using recursion in R:

1. Ensure that you have base cases that terminate the recursion.
2. Make sure that the recursive calls reduce the problem towards the base cases.
3. Be mindful of potential performance issues with deep recursion, as R may not optimize tail
recursion.

Recursion can be a powerful tool for solving problems that naturally exhibit a recursive
structure, but it should be used judiciously and with care to avoid unnecessary performance
overhead and stack overflow errors.

A Quicksort Implementation-Extended Extended Example:

# QuickSort function
quick_sort <- function(arr) {
# Base case: if the array has 0 or 1 elements, it's already sorted
if (length(arr) <= 1) {
return(arr)
}

# Choose a pivot element (in this case, we'll choose the first element)
pivot <- arr[1]

# Divide the array into three parts: elements less than the pivot,
# elements equal to the pivot, and elements greater than the pivot
less <- arr[arr < pivot]
equal <- arr[arr == pivot]
greater <- arr[arr > pivot]

R PROGRAMMING PREPARED BY:ARPITA JAIN MCA(II YEAR)


MODULE II

# Recursively sort the "less" and "greater" parts


sorted_less <- quick_sort(less)
sorted_greater <- quick_sort(greater)

# Concatenate the three parts to form the sorted array


sorted_arr <- c(sorted_less, equal, sorted_greater)

return(sorted_arr)
}

# Example usage:
unsorted_list <- c(5, 2, 9, 3, 6, 1, 8, 7, 4)
sorted_list <- quick_sort(unsorted_list)
print(sorted_list)

In this implementation:
1. quick_sort is a recursive function that takes an array arr as its argument.
2. The base case checks if the length of the array is 0 or 1. If so, it returns the array because it's
already sorted.
3. A pivot element is chosen. In this example, we select the first element of the array as the
pivot.
4. The array is divided into three parts: elements less than the pivot, elements equal to the pivot,
and elements greater than the pivot.
5. The quick_sort function is called recursively on the "less" and "greater" parts of the array.
6. Finally, the sorted parts are concatenated together to form the fully sorted array.

When you run this code with unsorted_list, you'll get the sorted list as the output.

QuickSort is a divide-and-conquer algorithm known for its efficiency. However, it's


important to note that this basic implementation may not be the most efficient for very large
lists, and you can optimize it further by choosing different pivot selection strategies or
implementing a more sophisticated partitioning scheme, such as the Lomuto or Hoare
partition scheme.
# Define a structure for tree nodes
TreeNode <- R6Class("TreeNode",
public = list(
key = NULL,
left = NULL,
right = NULL,
initialize = function(key) {
self$key <- key
self$left <- NULL
self$right <- NULL
}
)
)

R PROGRAMMING PREPARED BY:ARPITA JAIN MCA(II YEAR)


MODULE II

# Define the BinarySearchTree class


BinarySearchTree <- R6Class("BinarySearchTree",
private = list(
root = NULL,

# Recursive function to insert a key into the tree


insert_recursive = function(node, key) {
if (is.null(node)) {
return(TreeNode$new(key))
}
if (key < node$key) {
node$left <- self$insert_recursive(node$left, key)
} else if (key > node$key) {
node$right <- self$insert_recursive(node$right, key)
}
return(node)
},

# Recursive function to search for a key in the tree


search_recursive = function(node, key) {
if (is.null(node) || node$key == key) {
return(node)
}
if (key < node$key) {
return(self$search_recursive(node$left, key))
} else {
return(self$search_recursive(node$right, key))
}
},

# Utility function to perform an in-order traversal (for demonstration


purposes)
inorder_traversal_recursive = function(node) {
if (!is.null(node)) {
self$inorder_traversal_recursive(node$left)
cat(node$key, " ")
self$inorder_traversal_recursive(node$right)
}
}
),

public = list(
initialize = function() {

R PROGRAMMING PREPARED BY:ARPITA JAIN MCA(II YEAR)


MODULE II

self$root <- NULL


},

# Public method to insert a key into the tree


insert = function(key) {
self$root <- self$insert_recursive(self$root, key)
},

# Public method to search for a key in the tree


search = function(key) {
return(self$search_recursive(self$root, key))
},

# Public method to perform an in-order traversal (for demonstration


purposes)
inorder_traversal = function() {
self$inorder_traversal_recursive(self$root)
cat("\n")
}
)
)

# Example usage:
bst <- BinarySearchTree$new()
bst$insert(50)
bst$insert(30)
bst$insert(70)
bst$insert(20)
bst$insert(40)
bst$insert(60)
bst$insert(80)

bst$inorder_traversal() # In-order traversal to print sorted keys


# Output: 20 30 40 50 60 70 80

result <- bst$search(60)


if (!is.null(result)) {
cat("Key 60 found in the tree.\n")
} else {
cat("Key 60 not found in the tree.\n")
}
 We define a TreeNode class to represent individual nodes in the BST.
 We define a BinarySearchTree class that contains methods for inserting keys, searching for
keys, and performing an in-order traversal.

R PROGRAMMING PREPARED BY:ARPITA JAIN MCA(II YEAR)


MODULE II

You can create a new BST, insert keys into it, search for keys, and perform in-order
traversals as demonstrated in the example usage section.

This is a basic implementation of a BST in R, and you can further extend it by adding other
operations like deletion or additional traversal methods as needed.

R PROGRAMMING PREPARED BY:ARPITA JAIN MCA(II YEAR)

You might also like