0% found this document useful (0 votes)
82 views27 pages

R Programming Unit - 2 Complete Notes

Uploaded by

Mgm Mallikarjun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views27 pages

R Programming Unit - 2 Complete Notes

Uploaded by

Mgm Mallikarjun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Statistical Computing and R Programming

UNIT-II : R Programming Structures, Control Statements, Loops,–Looping Over Non-vector


Sets,- If Else, Arithmetic, and Boolean Operators and values, Default Values for Argument,
Return Values, Deciding Whether to explicitly call return-Returning Complex Objects,
Functions are Objective, No Pointers in R, Recursion, A Quicksort Implementation-Extended
Example, Error Handling.

R Programming Structures:
 In R, programming structures refer to the building blocks used to create programs and
scripts. These include elements that define the flow of execution, data handling, and logic.

Control Statements:

 Control structures in R are used to control the flow of execution of code depending on
conditions or for repetitive tasks. They help in decision-making, looping, and branching
logic.

Decision-making statements are: if, if-else, if...else if...else statements

1. if Statement

Definition:
 The if statement is used to execute a block of code only when a specified condition is TRUE.

Syntax:
if (condition)
{
# code to run if condition is TRUE
}

Example:
x <- 10

if (x > 0)
{
print("x is a positive number")
}

Output:
[1] "x is a positive number"

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 1


Statistical Computing and R Programming

2. if...else Statement

Definition:
 The if...else statement lets you execute one block of code if the condition is TRUE, and
another block if it is FALSE.
 An if-else statement is the if statement followed by an else statement. An if-else statement, else
statement will be executed when the boolean expression will false. In simple words, If a Boolean
expression will have true value, then the if block gets executed otherwise, the else block will get
executed.

Syntax:

if (condition)
{
# code if condition is TRUE
}
else
{
# code if condition is FALSE
}

Example:

age <- 16

if (age >= 18)


{
print("You are eligible to vote.")
}
else
{
print("You are not eligible to vote.")
}

Output:
[1] "You are not eligible to vote."

Explanation:
Since age >= 18 is FALSE, the code inside the else block runs.

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 2


Statistical Computing and R Programming

3. if...else if...else Statement

Definition:
 The if...else if...else statement is used when you want to check multiple conditions,
one after another.
 This statement is used to test various condition in a single if......else if statement. There are some
key points which are necessary to keep in mind when we are using the if.....else if.....else
statement.

Syntax:
if (condition1)
{
# code if condition1 is TRUE
}
else if (condition2)
{
# code if condition2 is TRUE
}
else
{
# code if all conditions are
FALSE
}

Example:
x <- 0

if (x > 0)
{
print("x is a positive
number")
}
else if (x < 0)
{
print("x is a negative number")
}
else
{
print("x is zero")
}

Output:
[1] "x is zero"

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 3


Statistical Computing and R Programming

R switch Statement

The switch statement is a selection control mechanism that changes the program’s flow based on the
value of an expression. It acts like a map and search system, selecting which block of code to run
depending on the expression’s value.

Purpose:

 Used instead of long if or if...else if statements when you want to compare a variable
against multiple values.
 It provides a multi-way branching mechanism that dispatches execution based on the expression.

How switch Works in R:

There are two main ways cases are selected:

1. Based on Index (Numeric Expression):


o If the expression evaluates to a number, it is used as an index to select from the list of
cases (which behave like a vector).
o Example: If the expression is 2, the second case is chosen.
2. Based on Matching Value (Character Expression):
o If the cases are named (like "case_1" = "value1"), then the expression’s value (a
character string) is matched against the case names.
o The first matching case’s value is returned.

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 4


Statistical Computing and R Programming

Examples:

1. Switch Based on Numeric Index

num <- 3

result <- switch(num,


"First case selected",
"Second case selected",
"Third case selected",
"Default case if index out of range")

print(result)

Output:

[1] "Third case selected"

Explanation:

 Since num is 3, the third case ("Third case selected") is chosen.


 If num was, say, 5 (and there are only 4 cases), it would select the last unnamed case as default.

2. Switch Based on Character Matching

fruit <- "banana"

result <- switch(fruit,


apple = "You selected apple",
banana = "You selected banana",
orange = "You selected orange",
"Unknown fruit")

print(result)

Output:

[1] "You selected banana"

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 5


Statistical Computing and R Programming

Loops in R
Definition:

Loops in R allow you to repeat a block of code multiple times, either a fixed number of times or until a
certain condition is met. This helps automate repetitive tasks.

Common Loop Types in R:


 for loop
 while loop
 repeat loop

Looping Over Non-Vector Sets


Sometimes you want to loop over objects that are not simple vectors, like lists, data frames, or
even expressions. Looping over such non-vector sets requires understanding how to access elements
properly.

1. for Loop

Definition:
 Executes a block of code once for each element in a sequence or collection.

Syntax:
for(variable in sequence)
{
# code to execute
}

Example: Looping Over a List (Non-vector)


my_list <- list(name="John", age=25, city="New York")

for (item in my_list)


{
print(item)
}
Output:
[1] "John"
[1] 25
[1] "New York"

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 6


Statistical Computing and R Programming

Example: Looping Over Data Frame Rows (Non-vector)


df <- data.frame(Name=c("Ankit", "Babu"), Age=c(30, 25))

for (i in 1:nrow(df))
{
print(paste(df$Name[i], "is", df$Age[i], "years old"))
}
Output:
[1] "Ankit is 30 years old"
[1] "Babu is 25 years old"

2. while Loop
Definition:
Repeats code while a condition is TRUE.
Syntax:
while (condition)
{
# code to execute
}

Example: Using while to Loop Until a Condition


count <- 1
while (count <= 3)
{
print(paste("Count is", count))
count <- count + 1
}
Output:
[1] "Count is 1"
[1] "Count is 2"
[1] "Count is 3"

3. repeat Loop
Definition:
Runs code indefinitely until explicitly stopped using break.
Syntax:
repeat
{
# code to execute
if(condition)
{
break
}
}

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 7


Statistical Computing and R Programming

Example: Using repeat with break


count <- 1
repeat
{
print(paste("Count is", count))
count <- count + 1
if (count > 3)
{
break
}
}
Output:
[1] "Count is 1"
[1] "Count is 2"
[1] "Count is 3"

Here are some useful and clear examples of for loops in R:

1. Basic for loop over numbers


# Print numbers 1 to 5
for (i in 1:5)
{
print(i)
}

2. Looping over a vector


# Print each element in a character vector
fruits <- c("apple", "banana", "cherry")

for (fruit in fruits)


{
print(paste("I like", fruit))
}

3. Loop with indexing over a vector


# Print index and value
numbers <- c(10, 20, 30)

for (i in 1:length(numbers))
{
cat("Index:", i, "- Value:", numbers[i], "\n")
}

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 8


Statistical Computing and R Programming

4. Nested for loops (e.g., matrix traversal)


# Fill and print a 3x3 matrix
mat <- matrix(1:9, nrow=3)

for (i in 1:nrow(mat))
{
for (j in 1:ncol(mat))
{
cat("Element at [", i, ",", j, "] is", mat[i, j], "\n")
}
}

5. Using for loop to create a new vector


# Square numbers and store them
squares <- numeric(5) # Preallocate for performance

for (i in 1:5)
{
squares[i] <- i^2
}

print(squares)

6. Conditional inside a loop


# Print only even numbers from 1 to 10
for (i in 1:10)
{
if (i %% 2 == 0)
{
print(i)
}
}

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 9


Statistical Computing and R Programming

FUNCTIONS IN R
Definition:

A function in R is a block of organized, reusable


code that performs a specific task. Functions help in
breaking down large programs into smaller,
manageable modules and are a core part of
programming in R.

R comes with a lot of built-in functions which provide users with various functionalities.

 A function can take inputs (arguments), perform computations, and return output (result).

Formal Definition:

A function is a group of instructions that:

 Takes input values (arguments)


 Processes or manipulates the data
 Returns an output (result)

Syntax of a Function in R
function_name <- function(arguments)
{
# Function body: statements
return(result) # Optional
}

Part Description

function_name <- Assigns the function to a name so it can be reused

function() Keyword to define a new function

arguments Inputs (parameters) passed into the function

{ ... } Curly braces contain the body (logic) of the function

(Optional) Explicitly returns a value; if omitted, last


return(result)
expression is returned

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 10


Statistical Computing and R Programming

Example:
add <- function(a, b)
{
result <- a + b
return(result)
}
add(3, 4)
# Output: [1] 7

Line Explanation
add <- function(a, b) Defines a function named add with two parameters a and b

{ Starts the function body (block of code)

result <- a + b Adds the values of a and b, and stores the result in a variable result

return(result) Returns the computed value to the caller

} Ends the function body

Advantages of Using Functions

Advantage Description
1. Code Reusability Write once, use multiple times without rewriting the same logic

2. Modularity Break a large program into smaller, logical components

3. Improved Clarity Easier to read and understand code, especially in large projects

4. Ease of Testing Individual functions can be tested independently

5. Maintainability Bugs are easier to locate and fix within a specific function

6. Avoid Redundancy Prevents duplication of code across the program

7. Scalability Makes it easier to expand and add new features to your program

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 11


Statistical Computing and R Programming

Types of Functions in R
There are mainly two types of functions in R:

1. Built-in Functions
2. User-defined Functions

1. Built-in Functions
 R contains a wide variety of built-in functions in the base R package. These are pre-defined
functions available to the user which perform common tasks without needing to implement them
manually.

Examples of built-in functions:

Built-in
Description Example
Function

sum() Calculates the sum of elements sum(c(1, 2, 3)) →6

mean() Calculates the average (mean) mean(c(4, 5, 6)) →5

median() Finds the median value median(c(1, 3, 5)) →3

max() Finds the maximum value max(2, 9, 7) →9

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 12


Statistical Computing and R Programming

Built-in
Description Example
Function

min() Finds the minimum value min(2, 9, 7) →2

sqrt() Calculates the square root sqrt(16) →4

abs() Returns the absolute value abs(-10) → 10

log() Calculates the natural logarithm log(10) → 2.302585

Rounds numbers to the specified


round() round(3.14159, 2) → 3.14
digits

length() Returns the length of an object length(c(1, 2, 3, 4)) →4

paste() Concatenates strings paste("Hello", "World") → "Hello World"

seq() Generates a sequence of numbers seq(1, 5) →12345

rep() Repeats values rep(2, 4) →2222

sort() Sorts the elements sort(c(3, 1, 2)) →123

unique() Returns unique elements unique(c(1, 2, 2, 3)) →123

is.na()
is.na(c(1, NA, 3)) → FALSE TRUE
Checks for NA (missing) values
FALSE

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 13


Statistical Computing and R Programming

Example of Built-in Functions in R:


# Sum of three numbers
print(paste("Sum is:", sum(3, 4, 5)))

# Square root of a number


print(paste("Square root is:", sqrt(55)))

# Absolute value of a number


print(paste("Absolute value is:", abs(-23.5)))

# Maximum of given numbers


print(paste("Maximum value is:", max(23, 52, 33, 44)))

# Minimum of given numbers


print(paste("Minimum value is:", min(23, 52, 33, 44)))

OUTPUT:

[1] "Sum is: 12"

[1] "Square root is: 7.41619848709566"

[1] "Absolute value is: 23.5"

[1] "Maximum value is: 52"

[1] "Minimum value is: 23"

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 14


Statistical Computing and R Programming

User-defined Functions in R :
 As the name suggests, user-defined functions are functions created by the user to perform specific
tasks. They help make code more readable, modular, and reusable.

How to Define a Function in R

Syntax:

function_name <- function(arg1, arg2, ...)


{
# Function body: code to perform the task
# Optional return statement
}

 function_name: Name you assign to the function


 arg1, arg2, ...: Arguments (parameters) passed to the function
 function: Keyword used to define the function
 Function body contains the actual code to be executed when called.
 The return() statement is optional — R returns the result of the last executed expression by
default.

Example: Creating User-defined Functions


# Function to add two numbers

add_numbers <- function(a, b)


{
sum <- a + b
return(sum)
}

# Calling the function

result <- add_numbers(10, 20)

print(result)

Output:

[1] 30

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 15


Statistical Computing and R Programming

Passing an Argument
 When you call a function in R, you can give values (arguments) to it.
 These values are then used inside the function.

Types of Argument Passing


1. Positional Arguments
 In R, when calling a function, the values are assigned to parameters based on
their order (position).
 The first argument → first parameter, second → second, and so on.
 Positional arguments = arguments passed in the same sequence as parameters
in the function definition.

Example
# Function definition
divide <- function(x, y)
{
return(x / y)
}

# Function call using positional arguments


result1 <- divide(20, 5) # x = 20, y = 5
result2 <- divide(100, 4) # x = 100, y = 4

print(result1) # Output: 4
print(result2) # Output: 25

OUTPUT:
4
25

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 16


Statistical Computing and R Programming

2. Named Arguments

 Instead of relying on position, we can pass values by explicitly writing the


parameter name.
 This makes the code clearer and order does not matter.

Example
# Function definition
divide <- function(x, y)
{
return(x / y)
}

# Function call using named arguments


result1 <- divide(x = 20, y = 5) # x = 20, y = 5
result2 <- divide(y = 5, x = 20) # order changed, but works the
same

print(result1) # Output: 4
print(result2) # Output: 4

3. Default Arguments

 In R, while defining a function, we can assign default values to parameters.


 If the caller doesn’t provide a value, R uses the default one.
 If a value is provided, it overrides the default.

Example
# Function with default argument
greet <- function(name = "User")
{
print(paste("Hello", name))
}

greet() # No argument → uses default → Output: "Hello User"


greet("Raju") # Argument given → overrides default → Output: "Hello Raju"

OUTPUT:
"Hello User"
"Hello Raju"

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 17


Statistical Computing and R Programming

Return Values in R Functions

 When a function finishes execution, it produces an output.


 In R, you can explicitly use the return() function or let R implicitly return the
last evaluated expression.

1. Explicit vs Implicit Return

 Explicit return: Use return(value) inside the function.


 Implicit return: If no return() is given, R returns the last statement
automatically.
# Explicit return
add_explicit <- function(a, b)
{
return(a + b)
}

# Implicit return
add_implicit <- function(a, b)
{
a + b # Last expression automatically returned
}

print(add_explicit(3, 4)) # 7
print(add_implicit(3, 4)) # 7

Tip: Use return() when you want to end function early or make return clearer.

2. Returning Complex Objects

 R functions can return any object – not just numbers or strings.


 Examples: vectors, lists, data frames, matrices, or even another function.

# Returning multiple values using a list


stats_fun <- function(x)
{
result <- list(
mean = mean(x),
median = median(x), OUTPUT
sd = sd(x)
)
return(result)
} [1] 30
data <- c(10, 20, 30, 40, 50)
res <- stats_fun(data) [1] 15.81139
print(res$mean) # Access mean
print(res$sd) # Access standard deviation

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 18


Statistical Computing and R Programming

3. Functions are Objects

 In R, functions are treated as first-class objects.


 This means you can:
o Assign them to variables
o Pass them as arguments to other functions
o Return a function from another function

# Assigning a function to a variable


square <- function(x)
{
x^2
}
f <- square
print(f(6)) # 36

# Returning a function
power_fun <- function(n)
{
function(x)
{
x^n
}
}

cube <- power_fun(3) # Returns a function that cubes


print(cube(2)) # 8

No Pointers in R

Unlike C or C++, R does not support pointers (direct memory addresses).

 In C, pointers are used for direct memory access and manipulation.


 In R, everything is an object and variables behave like references internally, but you cannot
access memory addresses directly.

Example (C vs R)

In C (with pointers):

int x = 10;
int *p = &x; // pointer p stores address of x

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 19


Statistical Computing and R Programming

In R (no pointers):

x <- 10
y <- x # y gets a copy/reference, but no direct memory address accessible
y <- 20
print(x) # x still 10

 In R, assignments are generally copy-on-modify.


 This means R handles memory internally; users don’t use pointers.

Recursion in R
 Recursion is when a function calls itself to solve a problem in smaller sub-problems.

Example 1: Factorial using Recursion

factorial_fun <- function(n)


{
if (n == 0)
{
return(1) # base case
}
else
{
return(n * factorial_fun(n - 1)) # recursive call
}
}

print(factorial_fun(5)) # 120

Example 2: Fibonacci sequence

fibonacci <- function(n)


{
if (n==0 || n==1)
{
return(n) # base case
}
else
{
return(fibonacci(n-1) + fibonacci(n-2)) # recursive call
}
}

print(fibonacci(6)) # 5

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 20


Statistical Computing and R Programming

A Quicksort Implementation:
 Quicksort is a divide-and-conquer sorting algorithm used to sort a list or array of elements. It
works by selecting a pivot element from the array and partitioning the other elements into two
groups:
 Elements less than the pivot
 Elements greater than the pivot
 The pivot is then in its correct position. The algorithm recursively applies the same process to the
two sub-arrays (less and greater) until the entire array is sorted.

It works on the principle of divide and conquer, breaking down the problem into smaller sub-
problems.

There are mainly three steps in the algorithm:

 Choose a Pivot: Select an element from the array as the pivot. The choice of pivot can vary
(e.g., first element, last element, random element, or median).

 Partition the List: Re arrange the array around the pivot. After partitioning, all elements
smaller than the pivot will be on its left, and all elements greater than the pivot will be on its
right. The pivot is then in its correct position, and we obtain the index of the pivot.

 Recursively Call: Recursively apply the same process to the two partitioned sub-arrays (left
and right of the pivot).

 Base Case: The recursion stops when there is only one element left in the sub-array, as a single
element is already sorted.

Here’s a basic overview of how the QuickSort algorithm works.

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 21


Statistical Computing and R Programming

R Program to quicksort implementation.


# Quicksort function
quicksort <- function(vec)
{
# Base case: if the vector has 0 or 1 element, it's already sorted
if(length(vec) <= 1)
{
return(vec)
}

# Choose the pivot (here we choose the first element)


pivot <- vec[1]

# Partition the vector into elements less than, equal to,


#and greater than the pivot
less <- vec[vec < pivot]
equal <- vec[vec == pivot]
greater <- vec[vec > pivot]

# Recursively sort the 'less' and 'greater' partitions and combine


return(c(quicksort(less), equal, quicksort(greater)))
}

# Example usage
numbers <- c(34, 7, 23, 32, 5, 62)
sorted_numbers <- quicksort(numbers)
print(sorted_numbers)

OUTPUT:

[1] 5 7 23 32 34 62

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 22


Statistical Computing and R Programming

Error Handling in R:

1. Definition

 Error handling in R is the process of managing unexpected situations (like invalid inputs,
missing files, or wrong operations) without crashing the program. Instead of stopping abruptly, R
can catch errors or warnings and handle them gracefully using functions like tryCatch() or
try().

2. Why use it (Purpose/Use)


 Prevent programs from crashing on errors.
 Provide custom error or warning messages.
 Execute cleanup code even when an error occurs.
 Debug or log errors for later analysis.

3. Syntax of tryCatch()
tryCatch(
expr ={
# Code you want to run
# risky code here
},
error = function(e)
{
#(Optional)
# code to handle error
},
warning = function(w)
{
#(Optional)
# code to handle warning
},
finally ={
# code that always runs (cleanup, closing files, etc.)
}
)

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 23


Statistical Computing and R Programming

Explanation of Each Part

1. expr
 This is the main block where you write the code that might cause an error or warning.
 If it runs fine → output is returned.
 If it fails → control moves to the error or warning handler.
Example:
expr = {
10 / 0 # risky code
}

2. error
 Runs only if an error occurs inside expr.
 The function gets an error object e containing details about what went wrong.
 You can print a message, log it, or handle it differently.
Example:
error = function(e)
{
print("There was an error!")
print(e)
}

3. warning
 Runs only if a warning occurs in expr.
 Warnings don’t stop execution by default, but tryCatch() allows you to intercept and handle
them.
 The function gets a warning object w.
Example:
warning = function(w)
{
print("There was a warning!")
print(w)
}

4. finally
 This block always runs no matter what happens (error, warning, or success).
 Useful for cleanup tasks like closing a file, disconnecting from a database, or printing a final
message.

Example:
finally = {
print("This will always run.")
}

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 24


Statistical Computing and R Programming

Examples
Example 1: Handling an Error

tryCatch(
expr =
{
x <- "a" + 1 # invalid operation → error
},
error = function(e)
{
print("Error occurred!")
print(e)
},
finally ={
print("Done.")
}
)

Output:

[1] "Error occurred!"


<simpleError in "a" + 1: non-numeric argument to binary operator>
[1] "Done."

Example 2: Handling a Warning

tryCatch(
expr = {
log(-5) # produces a warning (NaN)
},
warning = function(w)
{
print("Warning occurred!")
print(w)
},
finally = {
print("Done.")
}
)

Output:

[1] "Warning occurred!"

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 25


Statistical Computing and R Programming
<simpleWarning in log(-5): NaNs produced>
[1] "Done."

Example 3: Normal Execution (No Error/Warning)

tryCatch(
expr = {
result <- 10 / 2
print(result)
},
error = function(e) {
print("Error occurred!")
},
warning = function(w) {
print("Warning occurred!")
},
finally = {
print("Done.")
}
)

Output:

[1] 5
[1] "Done."

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 26


Statistical Computing and R Programming

Prof. Raju Vathari Tungal Degree College, Jamkhandi Page 27

You might also like