0% found this document useful (0 votes)
38 views

UNIT -2 R programming

This document covers file handling in R programming, detailing how to read and write various file formats including CSV, Excel, and XML. It explains functions like read.csv(), write.table(), and read.xlsx() for importing and exporting data, along with examples for practical application. Additionally, it discusses the importance of file management in preserving data across sessions.

Uploaded by

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

UNIT -2 R programming

This document covers file handling in R programming, detailing how to read and write various file formats including CSV, Excel, and XML. It explains functions like read.csv(), write.table(), and read.xlsx() for importing and exporting data, along with examples for practical application. Additionally, it discusses the importance of file management in preserving data across sessions.

Uploaded by

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

UNIT – 2

Reading and writing files, Programming, Calling Functions, Conditions and Loops:
stand-alone statement with illustrations in exercise 10.1, stacking statements, coding
loops, Writing Functions, Exceptions, Timings, and Visibility.

Reading and writing files, Programming

File Handling (Reading and writing files in R programming)


• In R, we can read data from files stored outside the R environment. We can also write
data into files which will be stored and accessed by the operating system.
• R can read and write into various file formats like csv, excel, xml etc.
Functions for Reading Data into R:

There are a few very useful functions for reading data into R.

1. read.table() and read.csv() are two popular functions used for reading tabular data into
R.
2. readLines() is used for reading lines from a text file.
3. source() is a very useful function for reading in R code files from a another R program.
4. dget() function is also used for reading in R code files.
5. load() function is used for reading in saved workspaces
6. unserialize() function is used for reading single R objects in binary format.

Reading Text Files:


1) Read Lines: To read the content of a text file line by line using the readLines() function.
2) Read Whole Text: To read the entire content of text file into a character vector, use the
readLines() function and then paste().
lines<-readLines(“sample.txt”)
text<-paste(lines, collapse=”\n”)
3) Reading CSV Files: To read from CSV(Comma-Separated Values) file, use the read.csv()
function.
data<-read.csv(“sample.csv”)
print(data)

Importing Data in R Script


We can read external datasets and operate with them in our R environment by importing data
into an R script. R offers a number of functions for importing data from various file formats.

Importing Data in R

1
First, let’s consider a data set that we can use for the demonstration. For this demonstration,
we will use two examples of a single dataset, one in .csv form and another .txt

Importing Data in R Script


Reading a Comma-Separated Value (CSV) File

Method 1: Using read.csv () Function Read CSV Files into R


The function has two parameters:
 file. choose(): It opens a menu to choose a CSV file from the desktop.
 header: It is to indicate whether the first row of the dataset is a variable name or
not. Apply T/True if the variable name is present else put F/False.
Example:

# import and store the dataset in data1


data1 <- read.csv(file. choose(), header=T)

# display the data


data1

Output:

Importing Data in R Script

Method 2: Using read.table() Function


This function specifies how the dataset is separated, in this case we take sep=”, “ as an
argument.
2
Example:

# import and store the dataset in data2


data2 <- read.table(file.choose(), header=T, sep=", ")
# display data
data2

Output:

Importing Data in R Script

Exporting Data from scripts in R Programming


Exporting Data from the R Programming Language is done on a prompt/terminal which is not
stored anywhere. But in the software industry, most of the programs are written to store the
information fetched from the program. One such way is to store the fetched information in a
file. So the two most common operations that can be performed on a file are:
 Importing Data to R scripts
 Exporting Data from R scripts
Exporting Data from R Scripts
When a program is terminated, the entire data is lost. Storing in a file will preserve one’s data
even if the program terminates. If one has to enter a large number of data, it will take a lot of
time to enter them all. However, if one has a file containing all the data, he/she can easily
access the contents of the file using a few commands in R. One can easily move his data from
one computer to another without any changes. So those files can be stored in various formats.
It may be stored in .txt(tab-separated value) file, or in a tabular format i.e .csv(comma-
separated value) file or it may be on the internet or cloud. R provides very easy methods to
export data to those files.
Exporting data to a text file
One of the important formats to store a file is in a text file. R provides various methods that
one can export data to a text file.
write.table():
The R base function write.table() can be used to export a data frame or a matrix to a text file.
Syntax: write.table(x, file, append = FALSE, sep = ” “, dec = “.”, row.names = TRUE,
col.names = TRUE)
Parameters:
x: a matrix or a data frame to be written.
file: a character specifying the name of the result file.
3
sep: the field separator string, e.g., sep = “\t” (for tab-separated value).
dec: the string to be used as decimal separator. Default is “.”
row.names: either a logical value indicating whether the row names of x are to be written
along with x, or a character vector of row names to be written.
col.names: either a logical value indicating whether the column names of x are to be written
along with x, or a character vector of column names to be written.

# R program to illustrate
# Exporting data from R

# Creating a dataframe
df = data.frame( "Name" = c("Amiya", "Raj", "Asish"), "Language" = c("R", "Python", "Java"), "Age" =
c(22, 25, 45) )
# Export a data frame to a text file using write.table()
write.table(df, file = "myDataFrame.txt", sep = "\t",row.names = TRUE, col.names = NA)

Output:

Exporting Data from scripts in R Programming


In This section of R studio we get the data saved as the name that we gave in the code. and
when we select that files we get this type of output.
"" "Name" "Language" "Age"
"1" "Amiya" "R" 22
"2" "Raj" "Python" 25
"3" "Asish" "Java" 45

write_tsv():
This write_tsv() method is also used for to export data to a tab separated (“\t”) values by
using the help of readr package.
Syntax: write_tsv(file, path)
Parameters:
file: a data frame to be written
path: the path to the result file

4
# R program to illustrate
# Exporting data from R

# Importing readr library


library(readr)

# Creating a dataframe
df = data.frame(
"Name" = c("Amiya", "Raj", "Asish"),
"Language" = c("R", "Python", "Java"),
"Age" = c(22, 25, 45) )
# Export a data frame using write_tsv()
write_tsv(df, path = "MyDataFrame.txt")

Output:
Name Language Age
Amiya R 22
Raj Python 25
Asish Java 45
Exporting data to a csv file
Another popular format to store a file is in a csv(comma-separated value) format. R provides
various methods that one can export data to a csv file.
write.table():
The R base function write.table() can also be used to export a data frame or a matrix to a csv
file.
Syntax: write.table(x, file, append = FALSE, sep = ” “, dec = “.”, row.names = TRUE,
col.names = TRUE)
Parameters:
x: a matrix or a data frame to be written.
file: a character specifying the name of the result file.
sep: the field separator string, e.g., sep = “\t” (for tab-separated value).
dec: the string to be used as decimal separator. Default is “.”
row.names: either a logical value indicating whether the row names of x are to be written
along with x, or a character vector of row names to be written.
col.names: either a logical value indicating whether the column names of x are to be written
along with x, or a character vector of column names to be written.

# R program to illustrate
# Exporting data from R

# Creating a dataframe
df = data.frame(
"Name" = c("Amiya", "Raj", "Asish"),

5
"Language" = c("R", "Python", "Java"),
"Age" = c(22, 25, 45) )
# Export a data frame to a text file using write.table()
write.table(df,
file = "myDataFrame.csv", sep = "\t", row.names = FALSE, )

Output:

write.csv():
This write.csv() method is recommendable for exporting data to a csv file. It uses “.” for the
decimal point and a comma (“, ”) for the separator.

# R program to illustrate
# Exporting data from R

# Creating a dataframe
df = data.frame(
"Name" = c("Amiya", "Raj", "Asish"),
"Language" = c("R", "Python", "Java"),
"Age" = c(22, 25, 45)
)

# Export a data frame to a text file using write.csv()


write.csv(df, file = "my_data.csv")

Output:

6
write.csv2():
This method is much similar as write.csv() but it uses a comma (“, ”) for the decimal point
and a semicolon (“;”) for the separator.
 R

# R program to illustrate
# Exporting data from R

# Creating a dataframe
df = data.frame(
"Name" = c("Amiya", "Raj", "Asish"),
"Language" = c("R", "Python", "Java"),
"Age" = c(22, 25, 45)
)

# Export a data frame to a text file using write.csv2()


write.csv2(df, file = "my_data.csv")

Output:

write_csv():

7
This method is also used for to export data to a comma separated (“, ”) values by using the
help of readr package.
Syntax: write_csv(file, path)
Parameters:
file: a data frame to be written
path: the path to the result file
 R

# R program to illustrate
# Exporting data from R

# Importing readr library


library(readr)

# Creating a dataframe
df = data.frame(
"Name" = c("Amiya", "Raj", "Asish"),
"Language" = c("R", "Python", "Java"),
"Age" = c(22, 25, 45)
)

# Export a data frame using write_csv()


write_csv(df, path = "MyDataFrame.csv")

Output:

Input as CSV File


The csv file is a text file in which the values in the columns are separated by a comma. Let’s
consider the following data present in the file named input.csv.

id, name, salary, start_date , dept


1, Rick, 623.3, 2012-01-01, IT
2, Dan, 515.2, 2013-09-23, Operations
3, Michelle, 611, 2014-11-15, IT
8
4, Ryan, 729, 2014-05-11, HR
5, Gary, 843.25, 2015-03-27, Finance
6, Nina, 578, 2013-05-21, IT
7, Simon, 632.8, 2013-07-30, Operations
8, Guru, 722.5, 2014-06-17, Finance
Reading a CSV File :
Following is a simple example of read.csv()function to read a CSV file available in your
current working directory:
data <-read.csv("input.csv")
print(data)
Analysing the CSV File :
By default the read.csv() function gives the output as a data frame. This can be easily checked
as follows. Also we can check the number of columns and rows.
data <- read.csv("input.csv")
print(is.data.frame(data)
print(ncol(data))
print(nrow(data))
Get the maximum salary:
# Create a data frame.
data <- read.csv("input.csv")
# Get the max salary from data frame.
sal <- max(data$salary)
print(sal)
Get the details of the person with max salary
We can fetch rows meeting specific filter criteria similar to a SQL where clause.
# Create a data frame.
data <- read.csv("input.csv")
# Get the max salary from data frame.
sal <- max(data$salary)
# Get the person detail having max salary.
retval <- subset(data, salary== max(salary))
print(retval)
Writing to a CSV File :
R can create csv file form existing data frame. The write.csv() function is used to create the
csv file.
This file gets created in the working directory.
# Create a data frame.
data <- read.csv("input.csv")
retval <- subset(data, as.Date(start_date) > as.Date("2014-01-01"))

9
# Write filtered data into a new file.
write.csv(retval,"output.csv")
newdata <- read.csv("output.csv")
print(newdata)
# Create a data frame.
data <- read.csv("input.csv")
retval <- subset (data, as.Date(start_date) > as.Date("2014-01-01"))
# Write filtered data into a new file.
write.csv(retval,"output.csv",row.names=FALSE)
newdata <- read.csv("output.csv")
print(newdata)
R- Excel Files:
Microsoft Excel is the most widely used spreadsheet program which stores data in the .xls
or .xlsx format.
• R can read directly from these files using some excel specific packages.
• Few such packages are - XLConnect, xlsx, gdata etc. We will be using xlsx package. R can
also write into excel file
using this package.
Install xlsx Package :
Verify and load the “xlsx” Package :
install.packages("xlsx")

# Verify the package is installed.


any(grepl("xlsx",installed.packages()))
# Load the library into R
workspace. library("xlsx")
When the script runs we get the following output.
[1] TRUE
Loading required package:
rJava Loading required
package: methods Loading
required package: xlsxjars

Input as xlsx File :


Open Microsoft excel. Copy and paste the following data in the work sheet named as sheet1

Save the Excel file as "input.xlsx". You should save it in the current working directory of the
R workspace.

Reading the Excel File :


The input.xlsx is read by using the read.xlsx () function as shown below.The result is stored
as a data frame in the R environment.

Data<- read.xlsx(“input.xlsx”, sheet Index =1)

10
Print(data)

R-XML Files:
You can read a xml file in R using the "XML" package. This package can be installed using
following command.

install.packages("XML")
Reading the XML file :
The xml file is read by R using the function xmlParse(). It is stored as a list in R.
library(“xml”)
library(“methods”)
result<-xmlParse(file=”input.xml”)
print(result)

XML to Data frame:


To handle the data effectively in large files we read the data in the xml file as a data frame.
Then process the data frame for data analysis.
library(“xml”)
library(“methods”)
result<-xmlToDataFrame(file=”input.xml”)
print(result)
Reading Excel Files:
The two excel files Sample_data1.xlsx and Sample_data2.xlsx and read from the working
directory.
# Working with Excel Files
# Installing required package
install.packages("readxl")

# Loading the package


library(readxl)

# Importing excel file


Data1 < - read_excel("Sample_data1.xlsx")
Data2 < - read_excel("Sample_data2.xlsx")

# Printing the data


head(Data1)
head(Data2)

Writing Files
After performing all operations, Data1 and Data2 are written into new files
using write.xlsx() function built in writexl package.

11
# Installing the package
install.packages("writexl")

# Loading package
library(writexl)

# Writing Data1
write_xlsx(Data1, "New_Data1.xlsx")

# Writing Data2
write_xlsx(Data2, "New_Data2.xlsx")

R-JSON Files :
JSON file stores data as text in human-readable format. Json stands for JavaScript Object
Notation. R can read JSON files using the Json package. In the R console, you can issue the
following command to install the rjson package.

install. Packages("rjson")

Reading the JSON file :


The JSON file is read by R using the function from JSON(). It is stored as a list in R.
library(“rjson”)
library(“methods”)
result<-fromJson(file=”input. Json”)
print(result)

Writing into a JSON file


One need to create a JSON Object using toJSON() function before he writes the data to a
JSON file. To write into a JSON file use the write() function.
Example:
Output:
[[1]]
[1] "sunflower" "guava" "hibiscus"

[[2]]
[1] "flower" "fruit" "flower"

Converting the JSON data into Dataframes


In R, to convert the data extracted from a JSON file into a data frame one can use
the as.data.frame() function.
Example:

12
# Writing into JSON file.

# Load the package required to read JSON files.


library("rjson")

# creating the list


list1 <- vector(mode="list", length=2)
list1[[1]] <- c("sunflower", "guava", "hibiscus")
list1[[2]] <- c("flower", "fruit", "flower")

# creating the data for JSON file


jsonData <- toJSON(list1)

# writing into JSON file


write(jsonData, "result.json")

# Give the created file name to the function


result <- fromJSON(file = "result.json")

# Print the result


print(result)

# Convert the file into dataframe

# Load the package required to read JSON files.


library("rjson")

# Give the input file name to the function.


result <- fromJSON(file = "E://example.json")

# Convert JSON file to a data frame.


json_data_frame <- as.data.frame(result)

print(json_data_frame)

Output:
ID Name Salary StartDate Dept
1 1 Mithuna 722.5 6/17/2014 IT
2 2 Tanushree 815.2 1/1/2012 IT
3 3 Parnasha 1611 11/15/2014 HR
4 4 Arjun 2829 9/23/2013 Operations
5 5 Pankaj 843.25 5/21/2013 Finance
13
Working with URLs
One can take datasets from any websites and extract the data and use them. This can be done
under any of two packages, namely RJSONIO and jsonlite.
Example:

# working with URLs

# import required library


library(RJSONIO)

# extracting data from the website


Raw <- fromJSON(
"https://data.ny.gov/api/views/9a8c-vfzj/rows.json?accessType=DOWNLOAD")

# extract the data node


food_market <- Raw[['data']]

# assembling the data into data frames


Names <- sapply(food_market, function(x) x[[14]])
head(Names)

Output:
[1] "LUCKY MART " "CUMBERLAND FARMS 1587 "
[3] "K&M SPORTS " "MASON&OLD RIDGE FARM "
[5] "HAMPTON CHUTNEY CO " "CM - HUTCHINSON "

CALLING FUNCTIONS:
R – Function :
A function is a set of statements organized together to perform a specific task. R has a large
number of in-built functions and the user can create their own functions. In R, a function is an
object so the R interpreter is able to pass control to the function, along with arguments that
may be necessary for the function to accomplish the actions
The function in turn performs its task and returns control to the interpreter as well as any
result which may be stored in other objects.
Definition :

An R function is created by using the keyword function. The basic syntax of an R function
definition is as follows:
function_name <- function(arg_1, arg_2, ...)
{
Function body
}
14
Function components :
• Function Name: This is the actual name of the function. It is stored in R environment as an
object with this name.
• Arguments: An argument is a placeholder. When a function is invoked, you pass a value to
theargument. Arguments are optional; that is, a function may contain no arguments. Also,
arguments can have default values.
• Function Body: The function body contains a collection of statements that defines what the
function does.
• Return Value: The return value of a function is the last expression in the function body to
be evaluated.
R has many in-built functions which can be directly called in the program without defining
them first. We can also create and use our own functions referred as user defined functions.

Function Types
Similar to the other languages, R also has two types of function, i.e. Built-in Function and
User defined Function. In R, there are lots of built-in functions which we can directly call in
the program without defining them. R also allows us to create our own functions.

Built-in function
The functions which are already created or defined in the programming framework are
known as built-in functions. User doesn't need to create these types of functions, and these
functions are built into an application. End-users can access these functions by simply calling
it. R have different types of built-in functions such as seq(), mean(), max(), and sum(x) etc.
1. # Creating sequence of numbers from 32 to 46.
2. print(seq(32,46))
5. print(mean(22:80))
7. # Finding the sum of numbers from 41 to 70.
8. print(sum(41:70))

User-defined function
R allows us to create our own function in our program. A user defines a user-define function
to
fulfil the requirement of user. Once these functions are created, we can use these functions
like
in-built function.

# Creating a function without an argument.


2. new.function <- function() {
3. for(i in 1:5) {
4. print(i^2)
5. }
6. }
7. new.function()

15
Calling functions :
# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
# Call the function new.function supplying 6 as an argument.
new.function(6)

Calling a Function with Argument Values(by position and by name)


The arguments to a function call can be supplied in the same sequence as defined in the
function or they can be supplied in a different sequence but assigned to the names of the
arguments.

16
Calling a Function with Default Argument
We can define the value of the arguments in the function definition and call the function
without supplying any argument to get the default result. But we can also call such functions
by supplying new values of the argument and get non default result.
# Create a function with arguments.
New.function<- function(a = 3,b =6) {
result <- a*b
print(result)
}
# Call the function without giving any argument.
New.function ()
# Call the function with giving new values of the argument.
New.function (9,5)
Lazy evaluation :Arguments to functions are evaluated lazily, which means so they are
evaluated only when needed by the function body.
# Create a function with arguments.
new.function<- function(a, b) {
print(a^2)
print(a)
print(b)
}
# Evaluate the function without supplying one of the arguments.
new.function(6)

17
Conditions and Loops
Conditions :
• In R programming, "conditions" typically refer to logical expressions or statements that
evaluate to either "TRUE" or "FALSE."
• These conditions are used in control structures like if statements, while loops, and for
loops to make decisions in the program.
• Conditions in R can involve comparisons (e.g., greater than, less than), logical operators
(e.g., AND, OR), and functions that return logical values. Here are some examples of
conditions in R:
Statement Description
if statement An if statement consists of a Boolean expression followed by one or more
statements.
if...else statement An if statement can be followed by an optional else statement, which
executes when the Boolean expression is false.
switch statement A switch statement allows a variable to be tested for equality against a list
of values.

R – IF Statements :

18
If else Statements:

19
If… else if..else.. Statements :

Switch Statements :

20
R- Loops :

• There may be a situation when you need to execute a block of code several number
of times. In general, statements are executed sequentially.
• The first statement in a function is executed first, followed by the second, and so
on.
• Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
the following is the general form of a loop statement in most of the programming languages
R programming language provides the following kinds of loop to handle looping
requirements. Click the following links to check their detail.
Loop Type Description
repeat loop Executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable.
while loop Repeats a statement or group of statements while a given
condition is true. It tests the condition before executing
the loop body.
for loop Like a while statement, except that it tests the condition at
the end of the loop body.
Repeat loop :

21
While loop :

22
Control Description
Statement
break Terminates the loop statement and transfers execution
statement to the statement immediately following the loop.
Next The next statement simulates the behaviour of R
statement switch.

for Loop :

Loop control statements:


• Loop control statements change execution from its normal sequence.
• When execution leaves a scope, all automatic objects that were created in that scope
are destroyed. R supports the following control statements.
Break Statement :

23
Next Statement :

Stacking Statement or nested statements:


1) You can put an "if statement" inside another "if statement."
2) This is called "nesting" or stacking" if statements.
3) It allows you to make complex decisions by checking multiple conditions one after the
other.
4) You can check conditions at different stages during your program's execution.

x <- 10
y <- 5
if (x > 5) { if (y > 2) {
print("Both x and y are greater than 5 and 2, respectively.")
} else {

24
print("x is greater than 5, but y is not greater than 2.")
}
} else {
print("x is not greater than 5.")
}
Writing functions
Defining a function allows you to reuse a chunk of code without endlessly copying and
pasting
It also allows other users to use your functions to carry out the same computations on their own
data or objects.
Function creation :

1. You can create a function in R using the `function` command.


2. You assign the function to a name, which you'll use to call it.
3. A function can have arguments (inputs), and these are specified in parentheses.
4. The arguments are like placeholders and don't have values initially.
5. Inside the function, you write the code that runs when the function is called.
6. You can use if statements, loops, and even call other functions within the function.
7. Arguments inside the function are treated as objects in its environment.
8. Functions should be documented to explain what they expect and do.
9. You can use the `return` command to send results back to the user.
10. If there's no `return`, the function will return the last result automatically.

Syntax :

Adding arguments :
Argument Declaration: Inside the function definition, you specify the arguments (inputs) the
function should accept. These arguments are like placeholders for the values you'll provide
when you call the function.
Example :
# Define a function to add two numbers
add_numbers <- function(num1, num2) {
result <- num1 + num2
return(result)
}
# Call the function with specific values
num1 <- 5
num2 <- 7
sum_result <- add_numbers(num1, num2)

Using return :

25
1. If a function doesn't have a `return` statement, it will end when it reaches the last line of
code in the function's body.
2. In such cases, the function will return the most recently assigned or created object in the
function.
3. If the function doesn't create or assign any objects, it will return ‘NULL`, which means
there's no specific result.
# Define a function to add two numbers
add_numbers <- function(num1, num2) {
result <- num1 + num2
return(result)
}
# Call the function with specific values
num1 <- 5
num2 <- 7
sum_result <- add_numbers(num1, num2)

Checking for missing argument:


1) The "missing" function checks if required arguments have been provided to a function.
2) It takes an argument tag and returns `TRUE` if that specified argument is missing.
1) This function helps prevent errors by ensuring that necessary arguments are provided
when calling a function.
2) For example, you can use "missing" to avoid errors when are quired argument is not
supplied.
3) "Missing" is particularly useful in the body code of a function to handle missing or
optional arguments effectively.

# Define a function that checks if an argument is missing


check_argument <- function(str1) {
if (missing(str1)) {
cat("The 'str1' argument is missing.\n")
} else {
cat("The 'str1' argument is present.\n")
}
}
Dealing with ellipses :
1) The ellipsis (or "..." notation) is a feature in R that allows you to pass extra, unspecified
arguments to a function without explicitly defining them in the argument list.
2) These extra arguments can be collected and used in the function’s code body.
3) Typically, the ellipsis is placed at the end of the argument list because it represents a
variable number of arguments.
4) It's a useful way to make functions more flexible by allowing users to provide additional
inputs beyond the explicitly defined arguments.
5) You can then pass these extra arguments to other functions within the code body.

26
6) The ellipsis is handy when you want to create functions that can handle various inputs
without explicitly specifying them in the function definition.
Specialized functions :
1. Helper Functions
- Designed to be called multiple times by another function.
- Can be defined inside the body of a parent function.
- Assist in specific tasks, improving code organization and readability.
• Externally defined
• Internally defined

Externally defined :
# External Helper Function Definition
multiplyByTwo <- function(x) {
result <- x * 2
return(result)
}
# Main Function Using the External Helper Function
mainFunction <- function(y) {
# Call the external helper function
result <- multiplyByTwo(y)
return(result)
}
# Example Usage
mainResult <- mainFunction(5)
print(mainResult) # Output: 10

Internally defined :
# Main Function with Internal Helper Function
mainFunction <- function(x) {
# Internal Helper Function Definition
square <- function(num) {
return(num^2)
}
# Using the Internal Helper Function
result <- square(x)
return(result)
}
# Example Usage
mainResult <- mainFunction(4)
print(mainResult) # Output: 16

Disposable Functions:
- Directly defined as an argument for another function.
- Temporary functions for specific tasks.
27
- Used briefly and discarded.
# Main Function with Disposable Function
mainFunction <- function(x, disposableFunc) {
# Using the Disposable Function as an Argument
result <- disposableFunc(x)
return(result)
}
# Disposable Function Definition
doubleValue <- function(num) {
return(num * 2)
}
# Example Usage
mainResult <- mainFunction(5, doubleValue)
print(mainResult) # Output: 10

Recursive Functions:
- Call themselves during execution.
- Break down problems into smaller, similar sub-problems.
- Suitable for repetitive patterns or structures.

# Recursive Function Example


factorial <- function(n) {
if (n == 0 | n == 1) {
return(1)
} else {
return(n * factorial(n - 1))
}
}
# Example Usage
result <- factorial(5)
print(result) # Output: 120

Exceptions:
The exception-handling facilities in R are provided through two mechanisms. Functions such
as stop or warning can be called directly or option such as “warn” can be used to control the
handling of problems. Exceptions can be handled using the tryCatch function. Exceptions or
errors occur when something unexpected happens during the execution of your code, such as
attempting to access a non-existent variable or divide by zero. Here’s how you can use
tryCatch to handle exceptions in R.

Example for warning command:


warn_test <- function(x){
if(x<=0){
warning("'x' is less than or equal to 0 but setting it to 1 and
28
continuing")
x <- 1
}
return(5/x)
}
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

Example for stop command:


error_test <- function(x){
if(x<=0){
stop("'x' is less than or equal to 0... TERMINATE")
}
return(5/x)
}
error_test(0)
Output:
Error in error_test(0) : 'x' is less than or equal to 0... TERMINATE

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.

Catching Errors with try Statements


When a function terminates from an error, it also terminates any parent functions. For
example, if function A calls function B and function B halts because of an error, this halts
execution of A at the same point. To avoid this severe consequence, you can use a try
statement to attempt a function call and check whether it produces an error.
Example:
v<-c(1,2,4,'0',5)
for (i in v)
{
try(print(5/i))
}
29
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")
})
}
check({10/2})
check({10/0})
check({10/'noe'})

30
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 Sys.time
command. This command outputs an object that details current date and time information
based on your system.
Sys.time()
Output: "2016-03-06 16:39:27 NZDT"

The Sys.sleep command makes R pause for a specified amount of time, in


seconds, before continuing.
Syntax:

Starttime <- Sys.time()


{
Func()
}
Endtime <- Sys.time()

Example:
Sleep_func <- function()
{
Sys.sleep(5)
}
Starttime <- Sys.time()
{
Sleep_func()
}
Endtime <- Sys.time()
Print(Endtime-Starttime)
Output:
5.008 sec

Explanation:
Store/Record the time before the execution in the variable Start time, 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:
As the name suggests, Global Variables can be accessed from any part of the program.

31
• 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()
# changing value of global variable
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

32

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy