R Programming: File Handling & Functions
R Programming: File Handling & Functions
UNIT II
Reading and writing files, Programming, Calling Functions, Conditions and Loops: standalone
statement with illustrations in exercise 10.1, stacking statements, coding loops, Writing Functions,
Exceptions, Timings, and Visibility.
Contributed Data-Sets
• Contributed datasets are created by the R-community.
• The datasets are not included in the base R installation.
• But the datasets are available through additional packages.
• You can install and load additional packages containing the required datasets.
For example,
R> [Link]("tseries") # to install the package
R> library("tseries") # to load the package
R> library(help="tseries") # to explore the data-sets in " tseries " package
R> help(“[Link]”) # to get info about the "[Link]" data-set
R> data([Link]) # To access the data in your workspace
R> [Link][1:5,] #display the first five records
Example: Suppose you have a file named [Link] with the following content:
Name Age City
Krishna 26 Mysore
Arjuna 31 Mandya
Karna 29 Maddur
• To read this data into R and create a data frame from it:
# Specify the file path
file_path <- "[Link]"
Output:
Name Age City
Krishna 26 Mysore
Arjuna 31 Mandya
Karna 29 Maddur
Web-Based Files
• [Link]() can be used for reading tabular data from web-based files.
• We can import data directly from the internet.
Example: To read tabular data from a web-based file located at the following URL:
[Link]
Spreadsheet Workbooks
• R often deals with spreadsheet software file formats, such as Microsoft Office Excel's `.xls` or
`.xlsx`.
• Exporting spreadsheet files to a table format, like CSV, is generally preferable before working
with R.
• To read this data into R and create a data frame from it:
# Specify the file path
file_path <- "[Link]"
# Use [Link] to read the CSV data into a data frame
my_data <- [Link](file_path)
# View the resulting data frame
print(my_data)
Output:
Example:
# Create sample data
x <- c(1, 2, 3, 4, 5)
y <- c(1, 4, 9, 16, 25)
# Open a JPEG graphics device and save the plot to a file
jpeg(filename = "scatter_plot.jpg", width = 800, height = 600)
# Replot the same graph (this time it will be saved as a JPEG)
plot(x, y, type = "p", main = "Scatter Plot Example")
[Link]() # Close the JPEG graphics device
Dept. of CS 5
Statistical Computing & R Programming 2025
• After opening the graphics device, we replot the same graph, which is now directed to the
JPEG file.
• Finally, we close the JPEG graphics device using [Link]().
Dept. of CS 6
Statistical Computing & R Programming 2025
Example: Program to illustrate usage of `dput` and `dget` # Create a sample list
my_list <- list( name = "Rama", age = 30,city = "Mysore")
# Use dput to serialize the list and save it to a text file
dput(my_list, file = "my_list.txt")
# Use dget to read and recreate the R object from the text file
recreated_list <- dget(file = "my_list.txt")
Dept. of CS 7
Statistical Computing & R Programming 2025
• We start by creating a sample list named my_list. This list contains various elements, including
a name, age, city, a vector of hobbies, and a Boolean value indicating whether the person is a
student.
• We then use the dput() function to write the my_list object to a plain-text file.
• The first argument to dput() is the object my_list.
• The second argument, file, specifies the name of the file my_list.txt where
• We use the dget() function to read the object from the specified file.
• The file argument in dget() specifies the name of the file from which to read the object (my_list.txt
in this case).
Calling Functions
Scoping
• Scoping-rules determine how the language accesses objects within a session.
• These rules also dictate when duplicate object-names can coexist.
Environments
• Environments are like separate compartments where data structures and functions are
stored.
• They help distinguish identical names associated with different scopes.
• Environments are dynamic and can be created, manipulated, or removed .
Dept. of CS 8
Statistical Computing & R Programming 2025
Local Environment
• Local environment is created when a function is called.
• Objects defined within a function are typically stored in its local environment.
• When a function completes, its local environment is automatically removed.
• These environments are isolated from the Global Environment.
• This allows identical argument-names in functions and the global workspace.
• Use: Local environments protect objects from accidental modification by other functions.
Dept. of CS 9
Statistical Computing & R Programming 2025
Search-path
• A search-path is used to access data structures and functions from different environments.
• The search-path is a list of environments available in the session.
• search() is used to view the search-path.
• Example:
search()
[1] ".GlobalEnv" "package:markovchain" "tools:rstudio" "package:stats"
[5] "package:graphics" "package:grDevices" "package:utils" "package:datasets"
[9] "package:methods" "Autoloads" "package:base"
• The search-path
i) starts at the global environment (.GlobalEnv) and
ii) ends with the base package environment (package:base).
• When looking for an object, R searches environments in the specified order.
• If the object isn't found in one environment, R proceeds to the next in the search path.
• environment() can be used to determine function's environment.
R> environment(seq)
<environment: namespace:base>
R> environment(arrows)
<environment: namespace:graphics>
Protected Names
• These names are associated with built-in functions and objects.
• These names are predefined and have specific functionalities.
• These names should not be directly modified or reassigned by users.
• Examples:
Functions like c(), [Link](), mean()
Objects like pi and letters.
Argument Matching
• Argument matching refers to the process by which function-arguments are matched
to their corresponding parameter-names within a function call.
• Five ways to match function arguments are
1) Exact matching
2) Partial matching
3) Positional matching
Dept. of CS 10
Statistical Computing & R Programming 2025
4) Mixed matching
5) Ellipsis (...) argument
Exact Matching
• Exact matching is the default argument matching method.
• In this, arguments are matched based on their exact parameter-names.
• Advantages:
1. Less prone to mis-specification of arguments.
2. The order of arguments doesn't matter.
• Disadvantages:
1. Can be cumbersome for simple operations.
2. Requires users to remember or look up full, case-sensitive tags.
• Example:
mat<-matrix(data=1:4,nrow=2,ncol=2,dimnames=list(c("A","B"), c("C","D")))
mat
C D
A1 3
B2 4
Partial Matching
• Partial matching allows to specify only a part of the parameter-name as argument.
• The argument is matched to the parameter whose name starts with the provided partial name.
• Example:
> mat <- matrix(nr=2, di=list(c("A","B"), c("C","D")), nc=2, dat=1:4)
> mat C D
A13
B24
• Advantages:
1. Requires less code compared to exact matching.
2. Argument tags are still visible, reducing the chance of mis-specification.
• Disadvantages:
1. Can become tricky when multiple arguments share the same starting letters in their tags.
2. Each tag must be uniquely identifiable, which can be challenging to remember.
Positional Matching
• Positional matching occurs when you specify arguments in the order in which the parameters
are defined in the function's definition.
• Arguments are matched to parameters based on their position.
• args() can be used to find the order of arguments in the function.
Example:
> args(matrix)
function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)
Dept. of CS 11
Statistical Computing & R Programming 2025
NULL
> mat <- matrix(1:4, 2, 2, F, list(c("A","B"), c("C","D")
> mat C D
A13
B24
• Advantages:
1) Results in shorter, cleaner code for routine tasks.
2) No need to remember specific argument tags.
• Disadvantages:
1) Requires users to know and match the defined order of arguments.
2) Reading code from others can be challenging, especially for unfamiliar functions.
Mixed Matching
• Mixed matching allows a combination of exact, partial, and positional matching in a
single function call.
• Example:
> mat <- matrix(1:4, 2, 2, dim=list(c("A","B"),c("C","D")))
> mat
CD
A 13
B 24
if Statement
The if statement is the simplest decision-making statement which helps us to take a decision on
the basis of the condition.
The block of code inside the if statement will be executed only when the boolean expression
evaluates to be true. If the statement evaluates false, then the code which is mentioned after the
condition will run.
Syntax:
if(boolean_expression)
{
// If the boolean expression is true, then statement(s) will be executed.
}
Example:
x <-20
y<-24
if(x<y)
{
print(x,"is a smaller number\n")
}
Output: 20 is a smaller number
If-else statement
There is another type of decision-making statement known as the if-else statement. 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.
Syntax:
if(boolean_expression)
{
// statement(s) will be executed if the boolean expression is true.
}
else
{
// statement(s) will be executed if the boolean expression is false.
}
Example:
a<- 100
if(a<20)
{
cat("a is less than 20\n")
}
else
{
cat("a is not less than 20\n")
Dept. of CS 13
Statistical Computing & R Programming 2025
}
cat("The value of a is", a)
Example:
marks=23;
if(marks>75){
print("First class")
}else if(marks>65){
print("Second class")
}else if(marks>55){
print("Third class")
}else{
print("Fail")
}
Output: First class
Dept. of CS 14
Statistical Computing & R Programming 2025
Nested if Statement
An if-else statement within another if-else statement is called nested if statement. This is used
when an action has to be performed based on many decisions. Hence, it is called as multi-way
decision
Syntax:
if(expr1)
{
if(expr2)
statement1 else
statement2
}
else
{
if(expr3)
statement3 else
statement4
}
Here, firstly expr1 is evaluated to true or false.
➢ If the expr1 is evaluated to true, then expr2 is evaluated to true or false.
• If the expr2 is evaluated to true, then statement1 is executed.
o If the expr2 is evaluated to false, then statement2 is executed.
➢ If the expr1 is evaluated to false, then expr3 is evaluated to true or false.
• If the expr3 is evaluated to true, then statement3 is executed.
o If the expr3 is evaluated to false, then statement4 is executed.
Example:
a <- 7
b <- 8
c <- 6
if (a > b) {
if (a > c) {
cat("largest = ", a, "\n")
}
else
{
cat("largest =", c, "\n")
}
} else {
if (b > c) {
Dept. of CS 15
Statistical Computing & R Programming 2025
switch Statement
This is basically a “multi-way” decision statement.
This is used when we must choose among many alternatives.
Syntax:
switch(expression,
case1, result1, case2,
result2,
Dept. of CS 16
Statistical Computing & R Programming 2025
...,...
default)
where
expression: The expression whose value you want to match against the cases.
case1, case2, ...: Values to compare against the expression. result1, result2, ...:
Code blocks when the expression matches the corresponding case.
default: (Optional) Code block when none of the cases match.
Example:
grade <- "B"
# Check the grade and provide feedback
switch(grade,
"A" = cat("Excellent!\n"),
"B" = cat("Well done\n"),
"C" = cat("You passed\n"),
"D" = cat("Better try again\n"),
cat("Invalid grade\n")
)
Output:
Well done
Coding Loops
• Loops are used to execute one or more statements repeatedly.
• There are 2 types of loops:
1) while loop
2) for loop
for Loop
• `for` loop is useful when iterating over elements in a vectors, lists or data- frames.
• Syntax:
for (variable in sequence) {
# Code to be executed in each iteration
}
where
variable: The loop-variable that takes on values from the sequence in each iteration.
sequence: The sequence of values over which the loop iterates.
Example:
numbers <- c(1, 2, 3, 4, 5)
for (i in numbers) { print(2*i) }
Output:
2 4 6 8 10
Dept. of CS 17
Statistical Computing & R Programming 2025
Example:
for (i in 1:3)
{
for (j in 1:3)
{
product <- i * j
cat(product, "\t")
}
cat("\n")
}
Output:
123
246
369
while Loop
• A while loop statement can be used to execute a set of statements repeatedly as long as a
given condition is true.
• Syntax:
while(expression)
{
statement1;
}
Dept. of CS 18
Statistical Computing & R Programming 2025
Output:
Welcome to R
Welcome to R
Welcome to R
[1,] 1 0 0 0
[2,] 0 1 0 0
[3,] 0 0 1 0
[4,] 0 0 0 1
3. Repeat Loop in R
The repeat loop executes indefinitely until explicitly stopped using the break statement. To terminate
the repeat loop we use a jump statement that is the break keyword.
Syntax:
repeat
{
statement
if( condition )
{
break
Dept. of CS 19
Statistical Computing & R Programming 2025
}
}
Ex: val = 1
repeat
{
print(val)
val = val + 1
if(val > 5)
{
break
}
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Jump statements:
Jump statements are used in loops to terminate the loop at a particular iteration or to skip a particular
iteration in the loop. The two most commonly used jump statements in loops are:
• Break Statement
• Next Statement
Break Statement:
The break Statement in R is a jump statement that is used to terminate the loop at a particular
iteration.
Syntax:
if (test_expression) {
break
}
Example a<-1
while (a < 10)
{
print(a)
if(a==5)
break
a=a+1
}
Output:
[1] 1
[1] 2
Dept. of CS 20
Statistical Computing & R Programming 2025
[1] 3
[1] 4
[1] 5
Next Statement
The next statement in R is used to skip the current iteration in the loop and move to the next iteration
without exiting from the loop itself.
Syntax: if (test_condition)
{
next
}
Example
x <- 1
while(x < 5)
{
x <- x + 1;
if (x == 3)
next;
print(x);
}
Output:
[1] 2
[1] 4
[1] 5
Example:
lazy_example <- function(a, b)
{
cat("Inside the function\n")
cat("a =", a, "\n")
cat("b =", b, "\n")
cat("Performing some operations...\n")
result <- a + b
cat("Operations completed\n") return(result)
}
# Create two variables
x <- 10
y <- 20
Dept. of CS 21
Statistical Computing & R Programming 2025
Output:
Inside the function
a = 10
b = 20
Performing some operations...
Operations completed
[1] 30
Output:
Default Area:6 Custom
Area:20
Output:
The argument 'x' is missing
The argument 'x' is provided with a value of 42
Dept. of CS 23
Statistical Computing & R Programming 2025
Dept. of CS 24
Statistical Computing & R Programming 2025
Figure 11-1: The default plot produced by a call to myfibplot, with thresh=150
Specialized Functions
Helper Functions
• These functions are designed to assist another function in performing computations
• They enhance the readability of complex functions.
• They can be either defined internally or externally.
Externally Defined Helper Functions
• These functions are defined in external libraries or modules.
• They can be used in your code w/o defining them within your program.
• They are typically provided by programming language or third-party libraries
• They provide commonly used functionalities.
• Example: Externally defined helper function ‘mean’ is used to find mean of 5 nos.
values <- c(10, 20, 30, 40, 50)
average <- mean(values)
cat("The average is:", average, "\n")
Output:
The average is: 30
Dept. of CS 25
Statistical Computing & R Programming 2025
Output:
The square of 5 is: 25
Output:
The area of the rectangle is: 15
Dept. of CS 26
Statistical Computing & R Programming 2025
Output:
The 5th Fibonacci number is: 4
Dept. of CS 27
Statistical Computing & R Programming 2025
Exception
When there’s an unexpected problem during execution of a function, R will notify you with either a
warning or an error.
In R, you can issue warnings with the warning command, and you can throw errors with the
stop command
#Calling Function
warn_test(0)
Output:
5
Warning message:
In warn_test(0) :
'x' is less than or equal to 0 but setting it to 1 and continuing
Explanation:
• In warn_test, if x is nonpositive, the function issues a warning, and x is
overwritten to be 1.
• warn_test has continued to execute and returned the value 5
Explanation:
• In error_test, on the other hand, if x is nonpositive, the function throws an error and
terminates immediately.
• The call to error_test did not return anything because R exited the function at the stop
command.
Dept. of CS 28
Statistical Computing & R Programming 2025
Example:
v<-c(1,2,4,'0',5)
for (i in v)
{
try(print(5/i))
}
Output:
5
2.5
1.25
Error in 5/I : non numeric argument to binary operator 1
Explanation:
• In the example given above we have code which has non-numeric value in the vector and we
are trying to divide 5 with every element of the vector.
• Using the try block we can see the code ran for all the other cases even after the error in one of
the iteration.
Using tryCatch
• The try block prevents your code from stopping but cannot provide a way to handle exceptions.
• Trycatch helps to handle the conditions and control what happens based on the conditions.
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
})
Example:
check<-function(expression){ withCallingHandlers(expression,
warning = function(w){ message("warning:\n", w)
},
error = function(e){ message("error:\n", e)
},
finally = { message("Completed")
Dept. of CS 29
Statistical Computing & R Programming 2025
})
}
check({10/2})
check({10/0}) check({10/'noe'})
Output:
Timing
• It’s often useful to keep track of progress or see how long a certain task took to complete.
• If you want to know how long a computation takes to complete, you can use the [Link]
command.
• This command outputs an object that details current date and time information based on
your system.
[Link]()
Output: "2016-03-06 16:39:27 NZDT"
The [Link] command makes R pause for a specified amount of time, in seconds, before
continuing.
Syntax:
Starttime <- [Link]()
{
Func()
Dept. of CS 30
Statistical Computing & R Programming 2025
}
Endtime = [Link]()
Example:
Sleep_func = function()
{
[Link](5)
}
Starttime = [Link]()
{
Sleep_func()
}
Endtime =[Link]()
Print(Endtime-Starttime)
Output:
5.008 sec
Explanation:
• Store/Record the time before the execution in the variable Starttime, then after the
execution of the function, store the time in Endtime variable.
• The difference between Endtime and Starttime gives the running time of the function.
Visibility
The location where we can find a variable and also access it if required is called the scope of a
variable. There are mainly two types of variable scopes:
Global Variables: Global Variables can be accessed from any part of the program.
• They are available throughout the lifetime of a program.
• They are declared anywhere in the program outside all of the functions or blocks.
• Declaring global variables: Global variables are usually declared outside of all of the
functions and blocks. They can be accessed from any portion of the program.
Example:
# global variable global
=5
# global variable accessed from within a function
display = function() {
print(global)
}
display()
Dept. of CS 31
Statistical Computing & R Programming 2025
global = 10
display()
Output:
5
10
Local Variables: Variables defined within a function or block are said to be local to those functions.
• Local variables do not exist outside the block in which they are declared, i.e. they can not
be accessed or used outside that block.
• Declaring local variables: Local variables are declared inside a block.
Example:
func = function()
{
# this variable is local to the function func() and cannot be accessed outside this function
age = 18
print(age)
}
cat("Age is:\n")
func()
Output: Age is :18
Question
1. Explain conditional constructs in details.
2. Explain the different looping statements in R?
3. Define Recursion function. Explain with an R – program
4. What are exceptions? Explain with an example
5. Write the syntax of standard deviation in R.
6. What are mean and mode?
7. Explain the following function with example.
[Link](),[Link](),[Link](),dput().dget()
8. Define Environment? Explain the different types of environments?
9. What is argument matching? Explain the different ways to match function arguments with
example?
10. Write a short note on specialized functions?
11. Write a short note on timing and visibility?
12. Define function? Explain default argument with example.
13. Write the general syntax of defining function in R. Explain its com
Dept. of CS 32