R Module-2
R Module-2
R Module-2
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
}
( Repeat Loop:
i <- 1
repeat {
print(i)
i <- i + 1
if (i > 5) break
}
(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
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
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{
statements
....
....
}
Example:
x <- 5
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"
[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
....
....
}
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
}
}
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
Output:
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10
} else {
for(i in 1:num) {
factorial = factorial * i
}
print(paste("The factorial of", num ,"is",factorial))
}
Sum of digits
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))
}
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
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:
if (n == 0 || n == 1) {
return(1)
} else {
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.
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.
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.
# 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]
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.
public = list(
initialize = function() {
# 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)
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.