0% found this document useful (0 votes)
30 views31 pages

R Programming Unit 2

Uploaded by

syed.mpasha01
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)
30 views31 pages

R Programming Unit 2

Uploaded by

syed.mpasha01
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

V Semester BCA – Statistical Computing with R Programming

HKBK DEGREE COLLEGE

BACHELOR OF COMPUTER APPLICATIONS


SEMESTER – V
2025-26

Course Material

STATISTICAL COMPUTING WITH R-


PROGRAMMING
(NEP SYLLABUS)

UNIT – II

Prepared by
Prof. S Vijaya Kumar
Senior Assistant Professor
Department of BCA
HKBK Degree College

S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 1


V Semester BCA – Statistical Computing with R Programming

UNIT II
Reading and writing files, Programming, Calling Functions, Conditions
and Loops: standalone statement, stacking statements, coding loops,
Writing Functions, Exceptions, Timings, and Visibility

Conditions and Loops

Control statements are used to control the execution and flow of the
program based on the conditions provided in the statements. Looping statements
are used to execute the statements repeatedly according to the criteria provided.

2.1 Decision making / Control statements

Decision-making is about deciding the order of execution of statements


based on certain conditions. In decision-making, the programmer needs to
provide some condition that is evaluated by the program, if it is true, statements
associated with true condition are executed if the condition is false, the
statements associated with false condition are executed.

The decision-making statements in R are as follows:

1. if statement
2. if-else statement
3. if-else-if ladder
4. switch statement

if statement

Keyword if tells the compiler that this is a decision control instruction


and the condition following the keyword if is always enclosed within a pair of
parentheses. If the condition is TRUE the statement gets executed and if
condition is FALSE then statement does not get executed.

Syntax:

S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 2


V Semester BCA – Statistical Computing with R Programming

if(condition)
{

statements

Where
if keyword
condition any valid relational or logical condition
statements  Valid R statements

PROGRAM 2.1 Program to demonstrate of simple if – Mark calculation

# Demonstration of simple if – Mark calculation


print("Enter the marks scored")
marks = [Link](readline())
print("Belongs to sports (y/n)")
ch=[Link](readline())
if (ch=='y')
marks = marks+ 10
print("Total Mark is " )
print(marks)

if-else statement
If-else, provides an optional else block which gets executed if the
condition for if block is false. If the condition provided to if block is true then
the statement within the if block gets executed, else the statement within the
else block gets executed.

Syntax:
S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 3
V Semester BCA – Statistical Computing with R Programming

if(condition)
{
true block statements
}else
{
false block statements
}

Where
if keyword
condition any valid relational or logical condition
statements  Valid R statements

PROGRAM 2.2 Program to demonstrate if..else

# R if-else statement Example


print("Enter two numbers")
a=[Link](readline())
b=[Link](readline())
if(a > b)
{
print(paste(a, "is greater"))
}else
{
print(paste(b, "is greater"))
}

if-else-if ladder
if-else-if ladder is used to make multiple decisions. The Expressions are
evaluated from the top to downwards. As soon as a true condition is found, the
statement associated with it is executed and the control is transferred to the
statement after the if-else-if construct. When all the conditions become false
then statement(s) after else will be executed. It takes the general form,
S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 4
V Semester BCA – Statistical Computing with R Programming

Syntax:

if(condition 1)
{
statement 1
} else if(condition 2)
{
statement 2
} else if(condition 3)
{
statements 3
}

Where
if keyword
condition any valid relational or logical condition
statements  Valid R statements

PROGRAM 2.3 Program to demonstrate if..else

# printing number names 0-3


print("Enter a number 0-3")
N =[Link](readline())
if (N==0)
{
print("ZERO")
}else if (N==1)
{
print(" ONE")
}else if (N==2)
{
print("TWO")
}else if (N==3)
S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 5
V Semester BCA – Statistical Computing with R Programming

{
print("THREE")
}
nested if-else statement
If the if statement contains another if statement is called nested-if –else
statemet.
Example
Write R program to find Largest of 3 three numbers

switch statement
In R, the switch statement is a control structure that allows for multi-way
branching. It evaluates an expression and selects one of several alternatives
based on the value of that expression. The switch function can handle both
numeric and character inputs, making it versatile for different scenarios. When
the expression is a number, switch returns the corresponding element from a list
of alternatives. If the expression is a character string, it matches the string to the
names of the alternatives and returns the corresponding value.

switch(EXPR,
case1 = { # Code for case1 },
case2 = { # Code for case2 },
...
default = { # Code if no match }
)

PROGRAM 2.4 Demonstration of switch statement

get_day_name <- function(day_number) {


day_name <- switch(day_number,
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
"Invalid day number")
S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 6
V Semester BCA – Statistical Computing with R Programming

return(day_name)
}

# Test the function


print(get_day_name(1)) # Output: "Monday"
print(get_day_name(5)) # Output: "Friday"
print(get_day_name(8)) # Output: "Invalid day number"

2.2 Looping Statements

Loops are fundamental constructs in programming that allow the


execution of a block of code multiple times under certain conditions. In R, loops
are particularly useful for automating repetitive tasks, iterating over objects, and
implementing complex algorithms.

Types of Loops in R

R provides three primary types of loops

i) for
ii) while
iii) repeat

for-loops
For loops are used to iterate over a sequence or a vector of elements. A
for-loop has a header that specifies the sequence and a body that contains the
code to be executed for each element. It takes the syntax,

for (value in sequence)


{
statement
}

S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 7


V Semester BCA – Statistical Computing with R Programming

PROGRAM 2.5 Demonstration of for loop


# R Program to display numbers from 1 to 5 using for loop in R.

for (val in 1: 5)
{

print(val)
}

PROGRAM 2. 6 Demonstration of for loop

# R program to illustrate for loop

# assigning strings to the vector


week <- c('Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday')

# using for loop to iterate over each string in the vector


for (day in week)
{

# displaying each string in the vector


print(day)
}

PROGRAM 2.7 for loop on a list

S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 8


V Semester BCA – Statistical Computing with R Programming

# Create a list of numbers


my_list <- list(1, 2, 3, 4, 5)

# Loop through the list and print each element


for (i in seq_along(my_list)) {
current_element <- my_list[[i]]
print(paste("The current element is:", current_element))
}

PROGRAM 2. 8 for loop on a matrix

# Create a 3x3 matrix of integers


my_matrix <- matrix(1:9, nrow = 3)

# Loop through the matrix and print each element


for (i in seq_len(nrow(my_matrix))) {
for (j in seq_len(ncol(my_matrix))) {
current_element <- my_matrix[i, j]
print(paste("The current element is:", current_element))
}
}

PROGRAM 2.9 for loop on a data frame

# Create a dataframe with some sample data


my_dataframe <- [Link](
Name = c("Guido van Rossum", "Dennis Ritchie", "Ross Ihaka", "James
Gosling"),
Name = c("Python", "C", "R", "Java"),

S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 9


V Semester BCA – Statistical Computing with R Programming

Gender = c("M", "M", "M", "M")


)

# Loop through the dataframe and print each row


for (i in seq_len(nrow(my_dataframe))) {
current_row <- my_dataframe[i, ]
print(paste("The current row is:", toString(current_row)))
}

while-loops
while loop execute a block of code as long as a specified condition is
true. They are useful when the number of iterations is not known in advance. It
takes the general form,
while ( condition )
{
statements
}

Where
condition valid R conditional statement
while keyword
statements  valid R statements

For instance, to add numbers until the sum reaches a certain threshold, we
can write as follows,
sum <- 0

i <- 1

while (sum < 10) {

sum <- sum + i

S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 10


V Semester BCA – Statistical Computing with R Programming

i <- i + 1

print(sum)

PROGRAM 2.10 Program to demonstrate the use of while loop

# R program to demonstrate the use of while loop

val = 1

# using while loop


while (val <= 5)
{
# statements
print(val)
val = val + 1
}

Repeat-loops
These execute a block of code indefinitely until a break condition is met.
They are less common but can be useful in certain scenarios.

For example, to increment a counter until it reaches a certain value, you


could use:

counter <- 0

repeat {

counter <- counter + 1


S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 11
V Semester BCA – Statistical Computing with R Programming

if (counter >= 10)

break

print(counter)

repeat and break


• repeat initiates an infinite loop
• not commonly used in statistical applications but they do have their uses
• The only way to exit a repeat loop is to call break

2.3 Standalone statements


In R programming, a standalone script is a script that can be executed
independently from the R console. These scripts are typically run using the
Rscript command rather than the standard R interpreter. Here are some key
points about standalone R scripts.

Shebang Line
Standalone R scripts usually start with a shebang line (#!/usr/bin/env
Rscript) which tells the system to use the Rscript interpreter to run the script.
Execution
These scripts can be executed directly from the command line, making
them useful for automation and batch processing.
Input and Output
Standalone scripts can handle user input and produce output files. For
example, they can read data from the console or files and write results to files.

2.4 Stacking Statement


In R programming, stacking typically refers to transforming data from a
wide format to a long format. This is useful for data analysis and visualization,
as many functions and packages in R prefer data in long format. The stack()
function is commonly used for this purpose.

S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 12


V Semester BCA – Statistical Computing with R Programming

PROGRAM 2.11 Program to demonstrate stacking statements


# Load the tidyr package
library(tidyr) # Tidy Messy Data

# Original data frame


data <- [Link](
Person = c('Anbu', 'Lysa', 'Kadhambari'),
Height = c(170, 160, 180),
Weight = c(70, 60, 80)
)

# Print original data frame


print("Original Data Frame:")
print(data)

# Stack the data frame


stacked_data <- stack(data, select = -Person)

# Use pivot_longer to stack the data frame


stacked_data <- pivot_longer(data, cols = c(Height, Weight), names_to =
"Measurement", values_to = "Value")
print(stacked_data)

2.5 Function

A function is a block of code designed to perform a specific task.


Functions help in organizing code, making it reusable, and avoiding repetition

Creating a Function
To create a function in R, we can use the function keyword. It takes the
general format,

S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 13


V Semester BCA – Statistical Computing with R Programming

function_name <- function(parameters)


{
# Function body
}

Where
function keyword
function_name  name of the function
parameterslist of argument
For example,
add_numbers <- function(a, b)
{
result <- a + b
return(result)
}

Calling a Function
To call a function, we should use its name followed by parentheses,
including any arguments if required. For example
function_name (parameters)

sum <- add_numbers(5, 3)


print(sum) # Output will be 8

next and return


• next = (no parentheses) skips an element, to continue to the next iteration
• return = signals that a function should exit and return a given value

PROGRAM 2.12 Function to calculate the power of a number

# Function to calculate the power of a number


power <- function(base, exponent = 2)
{
result <- base^exponent
S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 14
V Semester BCA – Statistical Computing with R Programming

return(result)
}# Load the tidyr package
library(tidyr) # Tidy Messy Data

# Original data frame


data <- [Link](
Person = c('Anbu', 'Lysa', 'Kadhambari'),
Height = c(170, 160, 180),
Weight = c(70, 60, 80)
)

# Print original data frame


print("Original Data Frame:")
print(data)

# Stack the data frame


stacked_data <- stack(data, select = -Person)

# Use pivot_longer to stack the data frame


stacked_data <- pivot_longer(data, cols = c(Height, Weight), names_to =
"Measurement", values_to = "Value")
print(stacked_data) # Load the tidyr package
library(tidyr) # Tidy Messy Data

# Original data frame


data <- [Link](
Person = c('Anbu', 'Lysa', 'Kadhambari'),
Height = c(170, 160, 180),
Weight = c(70, 60, 80)
)

# Print original data frame


print("Original Data Frame:")
print(data)

S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 15


V Semester BCA – Statistical Computing with R Programming

# Stack the data frame


stacked_data <- stack(data, select = -Person)

# Use pivot_longer to stack the data frame


stacked_data <- pivot_longer(data, cols = c(Height, Weight), names_to =
"Measurement", values_to = "Value")
print(stacked_data)

# Calling the function with both arguments


print(power(3, 3)) # Output: 27

# Calling the function with only the base argument (uses default exponent)
print(power(4)) # Output: 16

# Using named arguments


print(power(exponent = 3, base = 2)) # Output: 8

2.6 Exceptions
In R, exceptions are used to handle errors and unusual conditions that
may arise during the execution of a program. Proper exception handling ensures
that code can gracefully manage unexpected situations without crashing. Here
are some key concepts and functions related to exception handling in R:

Key Functions for Exception Handling


stop()
Generates an error and stops the execution of the current function.
warning()
Generates a warning message but does not stop the execution.
try()
Executes an expression and catches any errors, allowing the program to
continue running.
tryCatch()
Provides more control over error handling by allowing us to specify
actions for different types of conditions (errors, warnings, etc.).

S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 16


V Semester BCA – Statistical Computing with R Programming

stop() - Stops execution with an error. warning() - Continues execution


with a warning. message() -Continues execution with an informational message.

Exceptions takes the following general syntax

check = tryCatch(
{
expression
},
warning = function(w)
{
code that handles the warnings
},
error = function(e)
{
code that handles the errors
},
finally = function(f)
{
clean-up code
})

expression  is the main block of code to execute. If this code generates


a warning or an error, the corresponding handler will be invoked.

warning = function(w)  is a function that handles warnings. If a


warning occurs during the execution of an expression, this function will be
called.
w is the warning object that contains information about the warning.

error = function(e)  is a function that handles errors. If an error occurs


during the execution of an expression, this function will be called.
e is the error object that contains information about the error.

S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 17


V Semester BCA – Statistical Computing with R Programming

finally = function(f) is a function that is always executed at the end,


regardless of whether an error or warning occurred. It is useful for clean-up
tasks.
f is not typically used, but we can include it for consistency.

PROGRAM 2.13 Program that demonstrates error handling

# R program illustrating error handling

# Evaluation of tryCatch
check <- function(expression)
{

withCallingHandlers(expression,

warning = function(w)
{
message("warning:\n", w)
},
error = function(e)
{
message("error:\n", e)
},
finally =
{
message("Completed")
})
}

check({10/2})
check({10/0})
check({10/'noe'})

OUTPUT
> source("C:/RPROG/BCA/jk21.R")
Completed
S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 18
V Semester BCA – Statistical Computing with R Programming

Completed
Completed
error:
Error in 10/"noe": non-numeric argument to binary operator

PROGRAM 2. 14 Program that demonstrates error handling


safe_divide <- function(x, y)
{
tryCatch({
result <- x / y
return(result)
},
error = function(e)
{
message("Error: Division by zero is not allowed.")
return(NA)
})
}

# Test the function


x=safe_divide(10, 2) # Should return 5
print(x)
x=safe_divide(10, 0) # Should return NA and print an error message
print(x)

OUTPUT
> source("C:/RPROG/BCA/jk22.R")
[1] 5
[1] Inf

PROGRAM 2.15 Program that demonstrates Reading a file with try catch

read_file <- function(file_path)


{
tryCatch({
data <- [Link](file_path)
S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 19
V Semester BCA – Statistical Computing with R Programming

return(data)
},
error = function(e) {
message("Error: File not found or unable to read the file.")
return(NULL)
})
}

# Test the function


data=read_file("C:/RPROG/[Link]") # Should return the data
frame
print(data)
read_file("C:/RPROG/BCA/first.R") # Should return NULL and print an error
message

OUTPUT
> source("C:/RPROG/BCA/jk23.R")
Index [Link] [Link] [Link] Company
1 1 DD37Cf93aecA6Dc Sheryl Baxter Rasmussen Group
2 2 1Ef7b82A4CAAD10 Preston Lozano Vega-Gentry
3 3 6F94879bDAfE5a6 Roy Berry Murillo-Perry
4 4 5Cef8BFA16c5e3c Linda Olsen Dominguez, Mcmillan and Dono
van
5 5 053d585Ab6b3159 Joanna Bender Martin, Lang and Andrade
6 6 2d08FB17EE273F4 Aimee Downs Steele Group
7 7 EA4d384DfDbBf77 Darren Peck Lester, Woodard and Mitchell
8 8 0e04AFde9f225dE Brett Mullen Sanford, Davenport and Giles
…..

NOTE [first 8 records of 100 are shown]

PROGRAM 2. 16 Program that demonstrates Reading a file with try catch

analyze_data <- function(data)


{
S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 20
V Semester BCA – Statistical Computing with R Programming

tryCatch({
summary_stats <- summary(data)
return(summary_stats)
}, warning = function(w) {
message("Warning: Data contains missing values.")
return(NA)
}, error = function(e) {
message("Error: Invalid data input.")
return(NULL)
})
}

# Test the function


data <- [Link](a = c(1, 2, NA, 4), b = c(5, 6, 7, 8))
mydata=analyze_data(data) # Should return summary statistics and print a
warning message
print(mydata)

OUTPUT
> source("C:/RPROG/BCA/jk24.R ")
a b
Min. :1.000 Min. :5.00
1st Qu.:1.500 1st Qu.:5.75
Median :2.000 Median :6.50
Mean :2.333 Mean :6.50
3rd Qu.:3.000 3rd Qu.:7.25
Max. :4.000 Max. :8.00
NA's :1

2.7 File Handling in R Programming


In R Programming, handling of files such as reading and writing files can
be done by using in-built functions present in R base package.

Creating a File

S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 21


V Semester BCA – Statistical Computing with R Programming

Using [Link]() function, a new file can be created from console or


truncates if already exists. The function returns a TRUE logical value if file is
created otherwise, returns FALSE. It takes the general format,

[Link](”filename“)
where
filename name of the file that has to be created

For example
[Link]("[Link]")

Writing into a File


[Link]() function is used to write an object to a file. This function is
present in utils package in R and writes data frame or matrix object to any type
of file. It takes the general format,
[Link](x, file)

where

x indicates the object that has to be written into the file


file indicates the name of the file that has to be written

Renaming a File
The [Link]() function renames the file and return a logical value.
The function renames files but not directories. It takes the general form,

[Link](from, to)

where

from indicates current file name or path


to indicates new file name or path

for example,
[Link]("[Link]", "[Link]")

S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 22


V Semester BCA – Statistical Computing with R Programming

Checking the existence of a File


A file exists or not in current working directory can be checked using
[Link]() function. It returns TRUE logical value if file exists, otherwise
returns FALSE. It takes the general format,

[Link](filename)

where

filename  name of the file that has to be searched in the current working
directory
for example,
[Link]("[Link]")

Reading a File
Using [Link]() function , files can be read and output is shown as
dataframe. This functions helps in analyzing the dataframe for further
computations. It takes the general format,

[Link](file)

where
file indicates the name of the file that has to be read

List all Files


By using [Link]() function, all files of specified path will be shown in
the output. If path is not passed in the function parameter, files present in
current working directory is shown as output. It takes the format,

[Link](path)

where
path indicates the path
For example, to list the files in E drive
[Link]("E:/")
S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 23
V Semester BCA – Statistical Computing with R Programming

Copy a File
The [Link]() function in R helps us to create a copy of specified file
from console itself. It takes the format,

[Link](from, to)

where
from indicates the file path that has to be copied
to indicates the path where it has to be copied
For example
[Link]("C:/RPROG/[Link]", "E:/")

Create a Directory
The [Link]() function is used to create a directory in the path specified
in the function parameter. If path is not specified in function parameter,
directory is created in current working directory. It takes the form,

[Link](path)

where

path indicates the path where directory has to be created


For example,
[Link]("jk")
will create a folder named “jk” in the current working directory

PROGRAM 2.17 Program that demonstrates the reading a text file

# Read lines from a text file


lines <- readLines("c:/RPROG/BCA/[Link]")
print(lines)
S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 24
V Semester BCA – Statistical Computing with R Programming

OUTPUT
> source("C:/RPROG/BCA/jk30.R")
[1] "Eye is the lamp of body. If the eye is good, then the whole body is full of li
ght, if the eye is bad,then the whole body is full of darkness."

PROGRAM 2.18 Program that demonstrates the writing on to a text file

# Write lines to a text file


lines <- c("Eye is not satisfied with seeing, nor the ear filled with hearing!")
writeLines(lines, "c:/RPROG/BCA/[Link]")
print("File created")

OUTPUT
> source("C:/RPROG/BCA/jk31.R")
[1] "File created"

PROGRAM 2.19 Program that demonstrates the reading of a csv file

# Read data from a CSV file


data=read_file("C:/RPROG/[Link]")
print(data

OUTPUT
(Showing 3 records out of 100 records)
> source("C:/RPROG/BCA/jk30.R")
Index [Link] [Link] [Link] Company
1 1 DD37Cf93aecA6Dc Sheryl Baxter Rasmussen Group
2 2 1Ef7b82A4CAAD10 Preston Lozano Vega-Gentry
3 3 6F94879bDAfE5a6 Roy Berry Murillo-Perry

Note:
To download the sample CSV Files
[Link]

S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 25


V Semester BCA – Statistical Computing with R Programming

PROGRAM 2.20 Program that demonstrates the writing of a csv file

# Write to a CSV file using [Link]()

[Link](data, "C:/RPROG/BCA/[Link]", [Link] = FALSE)


print("file created")

OUTPUT
> source("C:/RPROG/BCA/jk31.R")
[1] "file created"

Note : It uses the previous program csv file data that is stored in the data
variable

PROGRAM 2.21 Program that demonstrates the reading of an excel file

# Read an Excel file using readxl::read_excel()


library(readxl)
data <- read_excel("C:/RPROG/student_list.xlsx")
print(data)

OUTPUT
> source("C:/RPROG/BCA/jk31.R")
# A tibble: 6 × 3
Sno Regno Name
<dbl> <chr> <chr>
1 1 U19MT22S001 Vijay Kumar Gupta
2 2 U19MT22S002 Prajwal
3 3 U19MT22S003 Prajwal
4 4 U19MT22S004 Tejas
5 5 U19MT22S005 Varsha
6 6 U19MT22S006 Hemanth

S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 26


V Semester BCA – Statistical Computing with R Programming

Note: You should have an excel file named student_list in the path
C:/RPROG/BCA/

PROGRAM 2.22 Program that demonstrates the writing of an excel file

# Install and load the writexl package


[Link]("writexl")
library(writexl)

# Create a data frame


df <- [Link](
Subject = c("DAA", "R Programming", "Cyber Security"),
code= c(5001, 5002, 5003)

# Write the data frame to an Excel file


write_xlsx(df, "C:/RPROG/v_sem_sub.xlsx")
print("Process completed")
OUTPUT
[1] "Process completed"

2.8 Timing
Timing is essential for optimizing code performance and ensuring
efficient execution. In R programming we have some common methods to
measure the execution time.

[Link]()
It Measures the time taken to evaluate an expression. Observe the
following code and its output.

print([Link]({
# Code to be timed
sum <- 0
for (i in 1:1000000) {
sum <- sum + i
S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 27
V Semester BCA – Statistical Computing with R Programming

}
}))

OUTPUT
user system elapsed
0.08 0.00 0.11

[Link]()
[Link]() captures the current time before and after the code execution
to calculate the duration. Observe the following code and its output.

start_time <- [Link]()


# Code to be timed
end_time <- [Link]()
duration <- end_time - start_time
print(duration)

OUTPUT
Time difference of 0.0001540184 secs

[Link]()
[Link]() provides more detailed timing information, including user,
system, and elapsed time.

ptm <- [Link]()


sum <- 0
for (i in 1:1000000)
{
sum <- sum + i
}
print([Link]() - ptm)

OUTPUT
user system elapsed
0.13 0.03 0.28
S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 28
V Semester BCA – Statistical Computing with R Programming

microbenchmark package
microbenchmark package offers precise timing for small code snippets.

[Link]("microbenchmark")
library(microbenchmark)
microbenchmark(
sum(1:1000000),
times = 100
)
print(sum)

OUTPUT
[1] 500000500000

2.9 Visibility
Visibility in R refers to the scope and accessibility of variables and
functions.

Global Environment
Variables created in the global environment are accessible throughout the
R session.

x <- 10 # Global variable

Local Environment
Variables created within a function are local to that function and not
accessible outside.

my_function <- function()


{
y <- 20 # Local variable
return(y)
}
S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 29
V Semester BCA – Statistical Computing with R Programming

Namespace
Each package has its own namespace, which helps avoid conflicts
between functions with the same name in different packages.

# Accessing a function from a specific package


dplyr::filter()

Masking
When two functions have the same name, the one loaded last masks the
previous one.

library(dplyr)
library(stats)
# dplyr::filter() is masked by stats::filter()

PROGRAM 2. 23 Example that combines timing and visibility concepts


# Timing a function execution
my_function <- function(n)
{
start_time <- [Link]()
sum <- 0
for (i in 1:n)
{
sum <- sum + i
}
end_time <- [Link]()
duration <- end_time - start_time
print(paste("Time taken:", duration))
return(sum)
}

# Calling the function


result <- my_function(1000000)
print(result)

S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 30


V Semester BCA – Statistical Computing with R Programming

# Visibility example
global_var <- 10

my_function <- function()


{
local_var <- 20
print(paste("Global variable:", global_var))
print(paste("Local variable:", local_var))
}

my_function()
# print(local_var) # This will cause an error as local_var is not accessible here

OUTPUT
> source("C:/RPROG/BCA/jk33.R")
[1] "Time taken: 0.079524040222168"
[1] 500000500000
[1] "Global variable: 10"
[1] "Local variable: 20"

S Vijaya Kumar, Senior Assistant Professor, HKBK Degree College Page 31

You might also like