0% found this document useful (0 votes)
2 views37 pages

Unit 2 R Programming

This document provides a comprehensive overview of R programming, focusing on file input/output operations, user input handling, output functions, conditional statements, looping constructs, and function definitions. It includes examples demonstrating how to read/write files, take user input, display output, and implement control flow using conditional and looping statements. The document serves as a practical guide for data import/export tasks and basic programming constructs in R.

Uploaded by

manjunathmg033
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)
2 views37 pages

Unit 2 R Programming

This document provides a comprehensive overview of R programming, focusing on file input/output operations, user input handling, output functions, conditional statements, looping constructs, and function definitions. It includes examples demonstrating how to read/write files, take user input, display output, and implement control flow using conditional and looping statements. The document serves as a practical guide for data import/export tasks and basic programming constructs in R.

Uploaded by

manjunathmg033
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

Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming
Unit 2
R Programming
In R programming, reading and writing files involves various functions that allow you to interact
with files on your computer. Here’s a detailed explanation along with examples for reading and
writing files in R.

Reading Files in R
Reading Text Files
1. Reading from Text Files (CSV, TXT, etc.):
o Use [Link]() or [Link]() for reading tabular data from CSV files.
o Use readLines() for reading lines from a text file.
Example:
# Reading from a CSV file
data <- [Link]("[Link]")
# Reading from a text file
lines <- readLines("[Link]")

2. Reading Excel Files:


 Use readxl package or openxlsx package to read Excel files.
Example
library(readxl)
data <- read_excel("[Link]")

Writing Files in R
Writing Text Files
1. Writing to Text Files:
o Use [Link]() or [Link]() for writing data frames to CSV files.
o Use writeLines() for writing lines of text to a text file.
Example:
# Writing to a CSV file
[Link](data, "[Link]")
# Writing lines to a text file
lines <- c("Line 1", "Line 2", "Line 3")
writeLines(lines, "[Link]")

1
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

2. Writing to Excel Files:


 Use [Link]() from the openxlsx package to write data frames to Excel files.

Example using openxlsx:


library(openxlsx)
[Link](data, "[Link]")

These functions provide robust capabilities for handling various file formats and are
essential for data import/export tasks in R programming. Adjust these examples based on your
specific file formats and requirements.

R programming with input and output statements


In R programming, input and output (I/O) operations allow you to interact with the user and
display or store results. Here’s how you can handle I/O operations in R with examples:

Input Statements in R
1. Reading Input from the User:
o Use readline() to take a single-line input from the user.
o For numeric input, you can convert the string input to a numeric type using
[Link]().
Example:
# Reading the first number from the user
num1 <- [Link](readline(prompt = "Enter the first number: "))
# Reading the second number from the user
num2 <- [Link](readline(prompt = "Enter the second number: "))
# Adding the two numbers
sum <- num1 + num2
# Displaying the result
cat("The sum of", num1, "and", num2, "is:", sum, "\n")

Output
Enter the first number: 10
Enter the second number: 10

The sum of 10 and 10 is: 20

2
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Reading Multiple Values:


In R programming, reading multiple values typically refers to capturing multiple
inputs either from the user or from a dataset. This can be done in various ways depending
on the source of the data (e.g., console input, files, or other data structures).
R allows you to read user input from the console using functions like readline(), scan(), or
readLines(). Here’s how you can use them:

Using readline() for Multiple Inputs:


Example
# Prompting user for input one at a time
x <- [Link](readline(prompt = "Enter the first number: "))
y <- [Link](readline(prompt = "Enter the second number: "))

Example:
# Reading the first number from the user
num1 <- [Link](readline(prompt = "Enter the first number: "))
# Reading the second number from the user
num2 <- [Link](readline(prompt = "Enter the second number: "))
# Adding the two numbers
sum <- num1 + num2
# Displaying the result
cat("The sum of", num1, "and", num2, "is:", sum, "\n")

Output
Enter the first number: 10

Enter the second number: 10

The sum of 10 and 10 is: 20

Using scan() to Read Multiple Values at Once:


R program that uses the scan() function to read multiple values from the console:
Example:
# Reads multiple numeric values from the console
numbers <- scan()
print(numbers)

3
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Program
#reading two numbers from the user
numbers <- scan(what=numeric(), nmax=2)
#adding the two numbers
result <-sum(numbers)
#displaying the result
cat(“The sum is:”,result)

Output
1: 10
2: 20
The sum is: 30

Reading file using scan()


The scan() function in R can also be used to read data from a file instead of directly from the
console. This function is versatile and allows you to specify the type of data to be read, how the
data is separated, and much more.

Using scan() to Read Data from a File


Suppose you have a text file called [Link] that contains the following numeric data:
Example: [Link]
5 10 15 20
25 30 35 40
45 50 55 60
You can use scan() to read this data into R.

R Program to Read a File Using scan()

Example:
# Program to read numeric values from a file using scan()

# Specify the file path (replace with your actual file path)

file_path <- "C:/data/[Link]"

# Use scan() to read the data from the file

values <- scan(file = file_path)

# Display the collected values

cat("The values read from the file are:\n")

print(values)

4
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming
# Perform some basic operations on the data

cat("Total number of values:", length(values), "\n")

cat("Sum of the values:", sum(values), "\n")

cat("Mean of the values:", mean(values), "\n")

cat("Minimum value:", min(values), "\n")

cat("Maximum value:", max(values), "\n")

Output

The values read from the file are:

[1] 5 10 15 20 25 30 35 40 45 50 55 60

Total number of values: 12

Sum of the values: 390

Mean of the values: 32.5

Minimum value: 5

Maximum value: 60

Explanation of the Program:


1. File Path: The file path is specified using the file_path variable. Ensure that the path
points to the correct location of your file. If the file is in your working directory, you can
simply use the file name.
2. Reading the File: The scan() function is used to read the file by specifying the file
argument. By default, scan() reads numeric data from the file.
3. Display the Values: The program prints the values read from the file.
4. Additional Operations: The program also demonstrates how to calculate the sum and
mean of the values read from the file.
Output statement in R
In R, the output statements are used to display results, messages, or any other
information to the console or other output devices. The most common functions for generating
output are print(), cat(), and message(). Each of these functions serves different purposes
and is used in different contexts.

5
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Example:
1. print() Function:
The print() function is the most basic way to display the value of an object in R. It automatically
formats the output and is typically used to print the value of variables, results of calculations, or
objects like vectors, data frames, etc.
Example:
# Define a variable
x <- 42
# Use print() to display the value of the variable
print(x)
# You can also directly print the result of an expression
print(x + 10)

Output

2. cat() Function
The cat() function is used for concatenating and printing objects in a more flexible and user-
defined format. Unlike print(), cat() does not add quotes around strings and does not display
the position index [1].
Example
# Define some variables
name <- "Alice"
age <- 25
# Use cat() to output a formatted string
cat("Name:", name, "\nAge:", age, "\n")

Output

3. message() Function
The message() function is used to display diagnostic messages or warnings to the user. It is
similar to cat(), but it sends output to a different output stream, allowing messages to be
suppressed or redirected more easily.

6
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Example:
# Use message() to display a diagnostic message
message("This is a warning message.")

Output

Comparison of Output Functions


 print(): Automatically formats output, best for simple display of R objects (like vectors,
data frames, etc.).
 cat(): Flexible formatting, used for constructing more complex and readable output
strings.
 message(): Used for diagnostic messages or warnings, output can be suppressed or
redirected.

Example
# Define variables
name <- "Bob"
score <- 85
# Use print() to show a simple output
print(score)
# Use cat() to show a formatted message
cat("Student:", name, "- Score:", score, "\n")
# Use message() to show a warning or informational message
if (score < 50)
{
message("Warning: Score is below passing threshold.")
}
else
{
message("Congratulations! You passed.")
}
Output

7
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Conditional Statements
Conditional statements allow a program to make decisions and execute different code blocks
based on certain conditions. Here’s a detailed explanation of various conditional statements with
if Statement:
The if statement in R evaluates a condition and executes a block of code if the condition is true.
The general syntax is
if (condition)
{
# Code to execute if condition is true
}
Examples:
age <- 18
if (age >= 18)
{

print("You are eligible to vote.")


}

Output

In this example, since age is 18, the condition age >= 18 is true, so "You are eligible
to vote." is printed.

2. if-else Statement
The if-else statement allows you to provide an alternative block of code that executes if the
condition is false.
Syntax:
if (condition)
{
# Code to execute if condition is true
}
else
{
# Code to execute if condition is false
}

8
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Example
age <- 16
if (age >= 18)
{
print("You are eligible to vote.")
}
else
{
print("You are not eligible to vote.")
}

Output

3. if-else if-else Statement


The if-else if-else statement allows checking multiple conditions sequentially.

Syntax:
if (condition1)
{
# Code to execute if condition1 is true
}
else if (condition2)
{
# Code to execute if condition2 is true
}
else if (condition3)
{
# Code to execute if condition3 is true
}
else
{
# Code to execute if none of the conditions are true
}

9
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Example:
# Input: student marks
marks <- 78
# Determine grade
if (marks >= 90)
{
grade <- "A"
} else if (marks >= 80)
{
grade <- "B"
} else if (marks >= 70)
{
grade <- "C"
} else if (marks >= 60)
{
grade <- "D"
} else
{
grade <- "F"
}
# Output grade
print(paste("Grade:", grade))Output

Output

4. switch Statement
The switch statement in R evaluates an expression and compares it against a list of possible
values, executing the corresponding block of code.
Syntax:
switch(expression,
case1 = { # Code for case1 },
case2 = { # Code for case2 },
case3 = { # Code for case3 },
default = { # Code for default case }
)

10
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Example
val1 = 6
val2 = 7
val3 = "s"
result = switch(
val3,
"a"= cat("Addition =", val1 + val2),
"d"= cat("Subtraction =", val1 - val2),
"r"= cat("Division = ", val1 / val2),
"s"= cat("Multiplication =", val1 * val2),
"m"= cat("Modulus =", val1 %% val2),
"p"= cat("Power =", val1 ^ val2)
)
print(result)

Output

Looping statements
In R programming, looping statements are used to execute a block of code repeatedly based on
certain conditions. The primary looping constructs in R are:
1. for loop: Used to iterate over a sequence (like a vector or list) and execute a block of
code for each element.
2. while loop: Repeats a block of code as long as a specified condition is true.
3. repeat loop: Repeats a block of code indefinitely until a break statement is encountered.

1. for Loop
Definition: The for loop iterates over a sequence (such as a vector or list) and executes a block
of code for each element in the sequence.
Syntax
for (variable in sequence)
{
# Code to be executed
}

11
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Example
# Using a for loop to print numbers from 1 to 5
for (i in 1:5)
{
print(i)
}
Output

Explanation:
 variable is i, which takes on each value in the sequence 1:5 (i.e., 1, 2, 3, 4, 5).
 The print(i) statement is executed for each value of i, printing the numbers 1 through 5.

2. while Loop
Definition: The while loop repeatedly executes a block of code as long as a specified condition
remains true.

Syntax:
while (condition)
{
# Code to be executed
# Update or modify the condition variable
}

Example
# Initializing the counter
i <- 1
# Using a while loop to print numbers from 1 to 5
while (i <= 5)
{
print(i)
i <- i + 1
}

12
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Output

3. repeat Loop
Definition: The repeat loop executes a block of code indefinitely until a break statement is
encountered.
Syntax:
repeat
{
# Code to be executed
# Use a break statement to exit the loop
}

Example
# Using a repeat loop to print numbers from 1 to 5
i <- 1 # Initialize the counter
repeat
{
print(i)
i <- i + 1 # Increment the counter
if (i > 5)
{ # Exit the loop if i is greater than 5
break
}
}

Output

13
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Explanation:
 The repeat loop continues indefinitely until the break statement is executed.
 print(i) prints the current value of i.
 i <- i + 1 updates the value of i.
 The if statement checks if i is greater than 5 and, if true, exits the loop with break.

Functions
Definition: A function in R is a block of code that performs a specific task and can be reused
multiple times within a program. Functions take inputs (called arguments), process them, and
return an output.

Syntax:
Defining a function
function_name <- function(arg1, arg2, ...)
{
# Code to execute
# Return value
}

Explanation:
 function_name is the name you give to the function.
 arg1, arg2, ... are the parameters or arguments passed to the function.
 The code block is the set of instructions that define what the function does.
 The return(value) statement (optional) specifies what the function should return. If not
explicitly used, the function returns the result of the last evaluated expression.

Example:
# Define a function to calculate the square of a number
square_number <- function(x)
{
result <- x^2 # Calculate the square of x
return(result) # Return the result
}
# Call the function with an argument
square_of_4 <- square_number(4)
# Print the result
print(paste("The square of 4 is", square_of_4))

14
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Output

Explanation:
1. Function Definition:
o square_number is the name of the function.
o function(x) specifies that the function takes one argument x.
o Inside the function, result <- x^2 calculates the square of x.
o return(result) returns the computed square.
2. Function Call:
o square_number(4) calls the function with 4 as the argument.
o The function computes the square of 4 and returns 16.

Calling a Function
Definition: Calling a function involves using the function name and providing the necessary
arguments to execute the function. This triggers the code within the function and returns the
result.

Syntax:
result <- function_name(argument1, argument2, ...)

Explanation:
 function_name is the name of the function you want to call.
 argument1, argument2, ... are the values you pass to the function’s parameters.
 result stores the value returned by the function.

Example
# Define a function to calculate the area of a rectangle
calculate_area <- function(length, width)
{
area <- length * width # Calculate the area
return(area) # Return the calculated area
}
# Call the function with specific arguments
rectangle_area <- calculate_area(5, 10)
# Print the result
print(paste("The area of the rectangle is", rectangle_area))

15
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Output

Types of functions
There are two types of functions
 Built in functions
 User defined functions

Built in functions
Definition: Built-in functions in R are pre-defined functions that come with R and its packages.
They perform common tasks and operations, and you can use them directly without needing to
define them yourself.
Syntax
function_name(argument1, argument2, ...)

Some of the built in function are:


1. mean()
Definition: The mean() function calculates the arithmetic mean (average) of a numeric vector.

Syntax:
mean(x, [Link] = FALSE)
 x is a numeric vector.
 [Link] is a logical value indicating whether to remove NA values before computation
(default is FALSE).

Example:
# Calculate the mean of a numeric vector
numbers <- c(10, 20, 30, 40, 50)
average <- mean(numbers)
print(paste("The average is", average))

Output

16
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

2. sum()
Definition: The sum() function calculates the total sum of a numeric vector.
Syntax:
sum()

Example
# Calculate the sum of a numeric vector
numbers <- c(5, 15, 25, 35, 45)
total_sum <- sum(numbers)
print(paste("The total sum is", total_sum))
Output

3. length()
Definition: The length() function returns the number of elements in a vector or list.
Syntax:
length(x)
 x is a vector or list.

Example
# Get the length of a numeric vector
numbers <- c(1, 2, 3, 4, 5)
vector_length <- length(numbers)
print(paste("The length of the vector is", vector_length))

Output

Explanation:
 length(numbers) returns the number of elements in numbers, which is 5.

4. sd()
Definition: The sd() function calculates the standard deviation of a numeric vector.
Syntax:
sd(x, [Link] = FALSE)

17
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Explanation
 x is a numeric vector.
 [Link] is a logical value indicating whether to remove NA values before computation
(default is FALSE).

Example
# Calculate the standard deviation of a numeric vector
numbers <- c(1, 2, 3, 4, 5)
standard_deviation <- sd(numbers)
print(paste("The standard deviation is", standard_deviation))

Output

5. round()
Definition: The round() function rounds numbers to a specified number of decimal places.
Syntax:
round(x, digits = 0)
Explanation
 x is a numeric vector.
 digits specifies the number of decimal places to round to (default is 0).

Example:
# Round numbers to 2 decimal places
values <- c(3.14159, 2.71828, 1.61803)
rounded_values <- round(values, 2)
print(paste("Rounded values are", toString(rounded_values)))

Output

Explanation:
round(values, 2) rounds each element in values to 2 decimal places: 3.14, 2.72, 1.62.

18
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

User defined functions


Definition: A user-defined function is a block of code that you define with a specific name,
parameters, and a set of instructions. You use these functions to perform tasks that are not
covered by built-in functions or to make your code more modular and readable.
Syntax
function_name <- function(parameter1, parameter2, ...)
{
# Code to execute
# Optional: return value
}
Explanation:
 function_name is the name you assign to the function.
 parameter1, parameter2, ... are the arguments that the function takes.
 The code block contains the operations or logic the function performs.
 The return(value) statement (optional) specifies the output of the function. If not
explicitly used, the function returns the result of the last evaluated expression.

1. Define the Function:


Example:
# Define a function to calculate the area of a triangle
calculate_triangle_area <- function(base, height)
{
area <- 0.5 * base * height # Calculate the area
return(area) # Return the result
}

Explanation:
 calculate_triangle_area is the name of the function.
 It takes two parameters: base and height.
 Inside the function, area <- 0.5 * base * height computes the area of the triangle.
 return(area) returns the computed area.

2. Call the Function:


Example:
# Call the function with specific arguments
triangle_area <- calculate_triangle_area(10, 5)
# Print the result
print(paste("The area of the triangle is", triangle_area))
19
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Full Example
# Define a function to calculate the area of a triangle
calculate_triangle_area <- function(base, height)
{
area <- 0.5 * base * height # Calculate the area
return(area) # Return the result
}
# Call the function with specific arguments
triangle_area <- calculate_triangle_area(10, 5)
# Print the result
print(paste("The area of the triangle is", triangle_area))

Output

Variable Scoping:
Definition: Variable scoping in R refers to the rules that determine the visibility and lifetime of
variables in different parts of your code. It defines where a variable can be accessed and
modified.
In R, variable scoping is influenced by the environment in which a variable is defined and
used. Here’s an explanation with an example:

Concepts of Variable Scoping:


1. Global Scope:
o Variables defined in the global environment (outside of any functions) are
accessible from anywhere in the script.

Example
# Define a global variable
global_var <- 10
# Function that uses the global variable
print_global <- function()
{
print(paste("Global variable value is:", global_var))
}
# Call the function
print_global()

20
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Output

2. Local Scope:
o Variables defined inside a function are local to that function. They are only
accessible within the function and are not visible outside of it.
Example:
# Define a function with a local variable
local_function <- function()
{
local_var <- 20 # Local variable
print(paste("Local variable value inside function is:", local_var))
}
# Call the function
local_function()
# Try to access the local variable outside the function
print(local_var) # This will produce an error

Output

3. Lexical Scoping:
o R uses lexical scoping, meaning that the function’s environment is determined
by where the function is defined, not where it is called. This allows functions
to access variables from their environment when they were created.

Example:
# Define an outer function
outer_function <- function(x)
{
# Define a variable in the outer function
outer_var <- x
# Define an inner function
inner_function <- function(y)
{
# Define a variable in the inner function
inner_var <- y
# Access and use variables from both inner and outer scopes
21
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming
result <- outer_var + inner_var
return(result)
}
# Call the inner function
inner_function(5)
}
# Call the outer function with an argument
result <- outer_function(10)
# Print the result
print(paste("The result is", result))

Output

Example:
# Define a variable in the global environment
global_variable <- "I am a global variable"

# Define a function with its own local variable


my_function <- function()

{
local_variable <- "I am a local variable"
print(global_variable) # Access the global variable
print(local_variable) # Access the local variable
}

# Call the function


my_function()

# Try to access the local variable outside the function


print(local_variable) # This will result in an error

Output

22
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Inline function:
An inline function in R refers to defining and using a function directly in a single line,
without giving it a formal name or storing it separately.
This is often done using anonymous functions—functions that are created on the fly
and typically used immediately in expressions or as arguments to other functions.
Example:
# Inline function to add two numbers
result <- (function(a, b)
{
return(a + b)
}
)(3, 4)
# Print the result
print(paste("The sum is", result))

Output

Exception:
In R programming, an exception is an error or unexpected event that occurs during
the execution of a program, disrupting the normal flow of the program. R provides
mechanisms to handle these exceptions so that the program can continue running or fail
gracefully.
Handling Exceptions in R
In R, exceptions are generally handled using try(), tryCatch(), or withCallingHandlers()
functions. These functions allow you to manage errors, warnings, and other conditions that may
arise during the execution of code.

1. Using try():
In R programming, the try() function is used to attempt the execution of an expression
that might generate an error, without stopping the execution of the entire script.
If an error occurs, try() catches the error and allows the program to continue
running. This is particularly useful when you want to ensure that your code continues executing
even if a particular operation fails.

General Syntax:
result <- try(expression, silent = FALSE)

23
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Explanation
 expression: The code block where an error might occur.
 silent: If set to TRUE, suppresses the error message. Default is FALSE.

Example
# Attempt to divide two numbers using try()
result <- try(10 / 0, silent = FALSE)
# Check if the result is an error
if (inherits(result, "try-error"))
{
print("An error occurred during division.")
}
else
{
print(paste("The result of division is:", result))
}

Output

[1] "Error in 10/0 : division by zero"

[1] "An error occurred during division."

2. Using tryCatch()
In R programming, tryCatch() is a more powerful and flexible tool than try() for
handling exceptions (errors, warnings, or other conditions). It allows you to specify how different
types of conditions should be handled, providing fine-grained control over what happens when
something goes wrong.

General syntax is
tryCatch({
# Code that might throw an exception
}, error = function(e) {
# Code to handle errors
}, warning = function(w) {
# Code to handle warnings
}, finally = {
# Code that should always run, regardless of an error or warning
})

24
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Explanation
 {}: The block of code you want to execute, which might generate an error or a warning.
 error = function(e): A block of code that runs if an error occurs. The error object e
contains details about the error.
 warning = function(w): A block of code that runs if a warning occurs. The warning
object w contains details about the warning.
 finally: A block of code that runs regardless of whether an error or warning occurs, useful
for cleanup tasks.

Example
# Define a function that might produce an error or warning
risky_operation <- function(x, y)
{
tryCatch(
{
if (y == 0)
{
warning("Warning: Division by zero")
}
result <- x / y
print(paste("The result is:", result))
}, error = function(e) {
print(paste("Error occurred:", e$message))
}, warning = function(w) {
print(paste("Warning occurred:", w$message))
}, finally = {
print("Execution of the function is complete.")
})
}
# Test with a valid division
risky_operation(10, 2)

# Test with a zero denominator (will trigger a warning)


risky_operation(10, 0)
# Test with an invalid operation (will trigger an error)
risky_operation("ten", 2)

25
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Output

Key Points:
 tryCatch() allows detailed handling of different types of conditions (error, warning,
etc.).
 error = function(e) is used to specify what happens when an error occurs.
 warning = function(w) is used to handle warnings similarly.
 finally is always executed, ensuring that any necessary final steps (like resource cleanup)
are taken.

3. withCallingHandlers()
Definition: withCallingHandlers() in R allows you to handle conditions (like errors, warnings,
or messages) immediately as they are signaled during code execution. Unlike tryCatch(), which
handles conditions after they occur, withCallingHandlers() lets you intervene right when the
condition is triggered.

Syntax
withCallingHandlers({
# Code that might signal a condition
}, warning = function(w) {
# Code to handle warnings
}, message = function(m) {
# Code to handle messages
}, error = function(e) {
# Code to handle errors
})

26
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Example
withCallingHandlers({
log(10) # Valid operation
log(-10) # This will produce a warning
}, warning = function(w) {
print("A warning occurred!")
}, message = function(m) {
print("A message occurred!")
}, error = function(e) {
print("An error occurred!")
})

Timings
In R programming, timing generally refers to measuring the amount of time taken by a block of
code or a function to execute. This is useful for performance analysis and optimization.

Key Functions for Timing in R:


1. [Link]():
o Measures the time taken to evaluate an R expression.
o Returns a list with three components:
 user: Time spent in user mode (the CPU time taken by the user's code).
 system: Time spent in system mode (the CPU time taken by the operating
system on behalf of the user's code).
 elapsed: The wall clock time (real-world time) that has passed during the
execution.
Example
[Link]({
result <- sum(runif(1e6))
})
Output

This example measures the time it takes to sum one million random numbers.

2. [Link]():
 Returns the cumulative CPU time used by the current R session up to the point when the
function is called.

27
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

 This can be useful for more granular tracking of CPU usage over the course of an entire R
session.

Example:
ptm <- [Link]()
result <- sum(runif(1e6))
[Link]() – ptm

Output

This example calculates the time taken by subtracting the start time from the end time.

3. microbenchmark:
 Part of the microbenchmark package, which provides more precise timing
measurements.
 Useful for comparing the performance of different code snippets or functions.

Example
# First install the microbenchmark package if not installed
#[Link]("microbenchmark")
library(microbenchmark)
microbenchmark(
rnorm(1000),
mean(rnorm(1000)),
times = 100 # Number of repetitions
)

Example

4. [Link]()
This can be used to get the system’s current time before and after code execution, and then
calculate the difference.

28
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Example:
start_time <- [Link]()
# Some time-consuming code here
end_time <- [Link]()
execution_time <- end_time - start_time
print(execution_time)

Output

Benchmarking with the bench package


In R, the bench package provides tools for accurate benchmarking. It allows you to measure the
performance of your code in terms of execution time, memory allocations, and garbage
collections. It's particularly useful for comparing the performance of multiple functions or code
snippets.

Key Features of the bench Package:


 Measures execution time.
 Tracks memory allocations and garbage collections.
 Provides accurate and repeatable benchmarks.
 Summarizes benchmarks with useful statistics (e.g., median, max, min).
Installing the bench Package
You need to install the package first if you haven't already:
[Link]("bench")

Benchmarking with bench::mark()


The main function for benchmarking is bench::mark(). It runs the expressions provided
multiple times and provides detailed results.
Example:
#[Link]("bench")
library(bench)
# Benchmark two different ways to calculate the sum of a sequence
results <- bench::mark(
sum_loop = {
total <- 0
for (i in 1:10000) {
total <- total + i
}
total

29
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

},
sum_builtin = sum(1:10000),
iterations = 100 # Number of times to repeat
)
# Print the results
print(results)

Output

Optimizing timing
Optimizing timing in R involves improving the performance of code by reducing its
execution time. By profiling and analyzing the timing of different sections of code, you can
identify bottlenecks and make adjustments to increase efficiency.
Here, explaining the process of optimizing timing with a practical example using the
[Link]() function for timing and then applying some optimizations to improve
performance.

Example: Optimizing a Function for Summing Values


Step 1: Measure Initial Timing
Let’s start by writing a simple function that sums all numbers in a vector using a loop and
measure how long it takes using [Link]().

# Inefficient function using a loop


sum_with_loop <- function(n)
{
total <- 0
for (i in 1:n)
{
total <- total + i
}
return(total)
}

30
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

# Timing the execution of the function


time_before_optimization <- [Link]({
result <- sum_with_loop(1e6)
})
print(time_before_optimization)

Output

This shows that the function took 0.03 seconds of user time.

Step 2: Apply Optimization


In this case, the loop is inefficient for a task that can be done more efficiently using a
built-in vectorized function like sum(). Vectorized operations in R are typically much faster
because they are optimized internally in R’s C code.
Here’s an optimized version using sum():

Example
# Optimized version using the sum() function
sum_optimized <- function(n)
{
return(sum(1:n))
}

# Timing the optimized function


time_after_optimization <- [Link]({
result <- sum_optimized(1e6)
})
print(time_after_optimization)

Output

The optimized version is significantly faster because the built-in sum() function is highly efficient
and avoids the overhead of a loop.

31
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming
Explanation of Syntax
 [Link](expr): Measures the time taken to evaluate expr. It returns a named
vector with components:
o user: Time spent by the CPU on the user code.
o system: Time spent on system-level operations.

o elapsed: Total wall clock time from start to end (most relevant for understanding
real-world performance).
 Optimization Steps:
1. Identify slow operations: Using [Link](), you can measure the execution time of
code blocks.
2. Replace inefficient code: Loops and non-vectorized operations are common performance
bottlenecks in R.
3. Use vectorized functions: Functions like sum(), mean(), apply(), and others are
optimized for performance.
4. Re-measure: After optimizing, use [Link]() again to see if the performance
improved.
This process of measuring, identifying bottlenecks, and optimizing can be repeated
for other parts of the code to ensure overall efficiency.

Visibility
In R, visibility determines how variables and values are accessed and whether the
results are printed or returned. When discussing visibility in terms of scope, it's important to
understand how global, local, and lexical scoping rules impact how variables are seen and
accessed in different parts of the program.
1. Global Scope
 Variables in the global scope are defined in the global environment, meaning they can
be accessed anywhere in the script unless overshadowed by local variables.
 When you define a variable at the global level (outside of any function), it’s visible to all
functions unless a local variable with the same name is defined.
Example
# Global variable
x <- 10
# Function accessing global variable
print_global <- function()
{
print(x) # x is taken from the global scope
}
print_global()
32
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Output
[1] 10

Here, the variable x is defined globally and is visible inside the function print_global().

2. Local Scope
 Variables in the local scope are defined within a function. They are visible only within
the function and not outside.
 If a variable is defined inside a function, it shadows any global variable with the same
name while the function is running.

Example
# Global variable
x <- 10
# Function with a local variable
print_local <- function()
{
x <- 5 # Local variable x
print(x) # x refers to the local variable
}
print_local() # Output: [1] 5
print(x) # Output: [1] 10 (Global variable remains unchanged)

Output
[1] 5

[1] 10

Here, inside the print_local() function, the local variable x is used, but the global x
remains unchanged after the function execution.

3. Lexical Scope
 Lexical scoping refers to the way R determines the value of a variable based on the
environment in which the function was defined, not where it is called.
 When a function is called, it first looks for variables in its local environment, then in the
parent environment (where the function was created), and continues up the chain until
it reaches the global environment.

33
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Example:
# Function that returns a function
outer_function <- function(a)
{
inner_function <- function(b)
{
a+b # a is taken from the lexical scope of outer_function
}
return(inner_function)
}
# Create a new function with a = 5 in its environment
new_function <- outer_function(5)
# Call the new function
new_function(3) # Output: [1] 8

Output
[1] 8

Accessing non visible objects


Many functions and objects in R packages may not be visible in the global environment. You can
still access non-exported objects or internal functions from packages using “ : : : “.
Example
# Install the 'stats' package if it's not installed (stats is base package, so usually no
need to install)
[Link]("stats") # Not required for base packages

# Load the package (also not needed for base packages)


library(stats)

# Access the non-visible '[Link]' function from the 'stats' package


kmeans_internal <- stats:::[Link]

# Use the internal function on sample data


data <- matrix(rnorm(100), ncol = 2)
result <- kmeans_internal(data, centers = 3)

# Print the result


print(result)

34
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

Explanation:
 Installing a package: [Link]("package_name") installs the package. In
this case, stats is part of base R, so no need to install or load it.
 Accessing non-visible function: stats:::[Link] accesses the internal, non-
exported [Link] function.
 Matrix data: matrix(rnorm(100), ncol = 2) creates a matrix with random numbers for
testing.
 Clustering: kmeans_internal(data, centers = 3) runs k-means clustering using the
non-visible function.

Packages
Packages in R are collections of functions, data sets, and documentation bundled together. They
extend R's base functionality and provide tools for specific tasks or analyses. Using packages
allows you to leverage the work of the R community and streamline your data analysis
processes.

Key Concepts
1. Installation:
o Packages need to be installed before they can be used.
o Installed packages are stored in a library directory and can be loaded into an R
session when needed.
Example
[Link]("package_name") # Install a package from CRAN

2. Loading:
 After installation, you need to load a package into your R session to use its functions and
datasets.
Example
library(package_name) # Load an installed package

3. Package Management:
 Use [Link]() to list all installed packages.
 Use [Link]("package_name") to uninstall a package.

4. Common Package Repositories:


 CRAN (Comprehensive R Archive Network): The main repository for R packages.
 Bioconductor: For packages related to bioinformatics and computational biology.

35
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming
 GitHub: Many developers host their packages on GitHub, which can be installed using
the devtools package.

5. Finding and Using Packages:


 Searching: You can find packages on CRAN or Bioconductor websites or using
[Link]().
 Documentation: Packages come with documentation that can be accessed using
?function_name or help(package = "package_name").

6. Examples of Popular Packages:


 ggplot2: For data visualization.
 dplyr: For data manipulation and transformation.
 tidyr: For tidying data.
 shiny: For building interactive web applications.
 lubridate: For working with date-times.

7. Creating Your Own Package:


 You can create custom packages to share your own functions and data. This involves
creating a package directory structure, adding documentation, and using tools like
devtools and roxygen2.

Example:
library(devtools)
create_package("path/to/package")

Example
# Install and load the 'ggplot2' package
[Link]("ggplot2")
library(ggplot2)

# Use a function from the 'ggplot2' package


data(mpg)
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
labs(title = "Engine Displacement vs. Highway MPG")

36
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.

Unit 2 R Programming

In this example:
 [Link]("ggplot2") installs the ggplot2 package.
 library(ggplot2) loads the package into the session.
 ggplot() is a function from ggplot2 used to create a scatter plot.

37

You might also like