0% found this document useful (0 votes)
12 views89 pages

UNIT II (R Programming)

The document provides an overview of R's built-in and contributed data sets, including how to access and read them using functions like data(), read.table(), and read.csv(). It also covers writing data to external files, creating plots in JPEG and PDF formats, and the concepts of environments and argument matching in R. Additionally, it explains reserved and protected names in R, along with methods for argument matching in function calls.

Uploaded by

raghuavabrath
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)
12 views89 pages

UNIT II (R Programming)

The document provides an overview of R's built-in and contributed data sets, including how to access and read them using functions like data(), read.table(), and read.csv(). It also covers writing data to external files, creating plots in JPEG and PDF formats, and the concepts of environments and argument matching in R. Additionally, it explains reserved and protected names in R, along with methods for argument matching in function calls.

Uploaded by

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

R-Ready Data-Sets

 R provides built-in data-sets and Data-sets are also


present in user-contributed-packages.
 data() can be used to access a list of the data-sets.
 The list of available data-sets is organized
i) alphabetically by name and
ii) grouped by package.
 Built-in Data-Sets: These datasets are included in the
base R installation
 • These data-sets are found in the package called
"datasets.“
 For example,
 R> library(help="datasets")
#To view summary of the data-sets within the package
 R> Help(“ChickWeight”)
# to get info about the "ChickWeight" data-set
 R> ChickWeight[1:5,]
#To display the first 5 records of ChickWeight
 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
 READING IN EXTERNAL DATA FILES: You can read
data from external files using various functions.
[Link] Format: Table-format files are plain-text files
with three features:
1) Header: If present, the header is the first line of the
file. The header provides column names.
2) Delimiter: The delimiter is a character used to
separate entries in each line.
3) Missing Value: A unique character string denoting
missing values This is converted to `NA` when
reading.
4) • Table-format files typically have extensions like
`.txt` or `.csv`.
Reading Table-Format Files
Syntax:
[Link](file, header = FALSE, sep = "")
where,
file: The name of the file from which data should be read. This can be a
local file path or a URL.
header: This indicates whether the first row of the file contains column
names Default is FALSE.
sep: This represents the field separator character. Default is an empty
string "“
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]"

 # Use [Link] to read the data into a data frame


 my_data <- [Link](file_path, header = TRUE, sep = "\t")

# View the resulting data frame


print(my_data)
Output:
Name Age City
Krishna 26 Mysore
Arjuna 31 Mandya
Karna 29 Maddur
 Reading 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]
 # Specify the URL of the web-based file
 url <- "[Link]
 # Use [Link] to read the data from the web-based
file my_data <- [Link](url, header = FALSE, sep = "\t")
 # View the resulting data frame
 print(my_data)
 Spreadsheet Workbooks:R often deals with spreadsheet software file
formats, such as Microsoft Office Excel's `.xls` or `.xlsx`.

Reading CSV Files


 [Link]() is used for reading comma-separated values (CSV) files.
 Syntax:
[Link](file, header = TRUE, sep = ",", )
Where,
file: The name of the file from which data should be read. This can
be a local file path or a URL.
header: This indicates whether the first row of the file contains
column names Default is FALSE.
sep: This represents the field separator character. Default is an
empty string "".
 Example: Suppose you have a CSV file named [Link] with the following
content:
 Name Age City
 Krishna 26 Mysore
 Arjuna 31 Mandya
 Karna 29 Maddur

# 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:
Name Age City
Krishna 26 Mysore
Arjuna 31 Mandya
Karna 29 Maddur
 Writing Out Data Files and Plots: You can write data to
external files using various functions.
 Writing Files: [Link]() is used to write a data frame to a text
file.
 Syntax:
 [Link](x, file, sep = " ",[Link] = TRUE, [Link]
= TRUE, quote = TRUE)
 Where,
x: The data frame or matrix to be written to the file.
file: The name of the file where the data should be saved.
sep: This represents the field separator character (e.g., "\t" for
tab-separated values, "," for comma-separated values).
[Link]: A logical value indicating whether row names
should be written to the file. Default is TRUE.
[Link]: A logical value indicating whether column
names should be written to the file. Default is TRUE
quote: A logical value indicating whether character and factor
fields should be enclosed in quotes. Default is TRUE.
 Example: Suppose you have a data frame my_data that you want to
write to a text file named "my_data.txt".
 # Sample data frame
 my_data <- [Link]( Name = c("Arjuna", "Bhima", "Krishna"), Age =
c(25, 30, 22), Score = c(85, 92, 78) )

 # Specify the file name


 file_name <- "my_data.txt"

# Use [Link] to save the data frame to a tab-separated text file


[Link](my_data, file = file_name, sep = "\t", [Link] = FALSE,
[Link] = TRUE, quote = TRUE)

# Confirmation message
cat(paste("Data saved to", file_name))
 Plots and Graphics Files
 A)Using `jpeg` function: jpeg() is used to create and
save plots as JPEG image files.
 You can specify parameters like the filename, width,
height, and quality of the JPEG image.
 Syntax: jpeg(filename, width, height)
 Where,
file: The name of the JPEG image file to which
the graphics will be written
width and height: The width and height of the
JPEG image in pixels.
 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")

# Close the JPEG graphics device


[Link]()
 B)Using `pdf` Function: pdf() can be used to create and save plots as PDF
files.
 Syntax:
 pdf(file, width, height)
 Where,
 file: The name of the PDF file to which the graphics will be written.
 width and height: The width and height of the PDF page in inches.
 Example: # Create a simple scatter plot
 x <- c(1, 2, 3, 4, 5)
 y <- c(1, 4, 9, 16, 25)
 # Open a PDF file for plotting
 pdf("scatter_plot.pdf", width = 6, height = 4)
 # Create a scatter plot
 plot(x, y, type = "p", main = "Scatter Plot Example", xlab = "X-axis", ylab = "Y
axis")
 # Close the PDF file
 [Link]()
 AD HOC OBJECT READ/WRITE OPERATIONS
 Most common input/output operations involve data-sets
and plot images.
 For handling objects like lists or arrays, you can use the
`dput` and `dget` commands.

 Using `dput` to Write Objects : dput() is used to write


objects into a plain-text file.
 It's often used to save complex objects like lists, data frames,
or custom objects in a human-readable format.
 Syntax: dput(object, file = "")
 where
 object: The R object you want to serialize into R code.
file: The name of the file where the data should be saved.
 Using `dget` to Read Objects: dget() is used to read
objects stored in a plain-text file created with `dput`.
 Syntax: dget(file)
 Where,
 file: The name of the file from which data should be
read.
 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")

 # Print the recreated R object
 print(recreated_list)
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.
 • Three important types of environments are:
 1) Global Environment
 2) Package Environments and Namespaces
 3) Local Environments
A)Global Environment: It is the space where all user-defined objects exist
by default.
• When objects are created outside of any function, they are stored in global
environment.
• Use: Objects in the global environment are accessible from anywhere
within the session. Thus they are globally available. •
`ls()` lists objects in the current global environment.
• Example:
R> v1 <- 9
R> v2 <- "victory"
R> ls()

[1] "v1" "v2"


B)Local Environment : Local environment is created
when a function is called.
 Objects defined within a function are typically stored
in its local environment.

# Define a function with a local environment


my_function <- function()
{
local_var <- 42
return(local_var)
}
 C)Package Environment and Namespace:
 It is the space where the package's functions and
objects are stored.
 • Packages have multiple environments, including
namespaces.
 • Namespaces define the visibility of package functions.
• Use: Package environments and namespaces allow
you to use functions from different packages without
conflicts.
 Syntax to list items in a package environment:
`ls("package:package_name")`.
 Example:
R> ls("package:graphics")
 #lists objects contained in graphics package
environment
 "abline" "arrows" "assocplot" "axis"
 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:
 R> search()
 ".GlobalEnv" "package:stats" "package:graphics"
“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 searchpath.
 • environment() can be used to determine function's
environment.
 R> environment(seq)
 <environment : namespace:base>
 R> environment(arrows)
 <environment:namespace:graphics>
RESERVED AND PROTECTED NAMES
 Reserved Names: These names are used for control
structures, logical values, and basic operations.
 • These names are predefined and have specific
functionalities.
 • These names are strictly prohibited from being used
as object-names.
 • Examples: if, else, for, while, function, TRUE, FALSE,
NULL
 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
 4) Mixed matching
 5) Ellipsis (...) argument
 A)Exact matching: Exact matching is the default argument matching
method.
 • In this, arguments are matched based on their exact parameter-names.

Example:
R> mat <- matrix(data=1:4, nrow=2, ncol=2, dimnames=list(c("A","B"),
c("C","D")))
R> mat
C D
A1 3
B2 4
 B)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:
 R> mat <- matrix(nr=2, di=list(c("A","B"), c("C","D")), nc=2, dat=1:4)

 R> mat
 CD
 A13
 B24
 C)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:
 R> args(matrix)
 function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames =
NULL)
 NULL R> mat <- matrix(1:4, 2, 2, F, list(c("A","B"), c("C","D")))
 R> mat

C D
A1 3
B2 4
D)Mixed Matching: Mixed matching allows a
combination of exact, partial, and positional matching in
a single function call.
• Example:
R> mat <- matrix(1:4, 2, 2, dim=list(c("A","B"),c("C","D")))
R> mat
CD
A13
B24
E)Dot-Dot-Dot: Use of Ellipses
• Ellipsis argument allows you to pass a variable number
of arguments to a function.
• Example:
Functions like `c()`, `[Link]()`, and `list()` •
Example:
R> args(list)
function (...)
NULL
 Conditions and Loops
 Conditional constructs allow programs to respond
differently depending on whether a condition is TRUE
or FALSE.
 There are 5 types of decision statements:
 1) if statement
 2) if else statement
 3) nested if statement
 4) else if ladder (stacking if Statement)
 5) switch statement
i)if Statement: The if statement is the simplest decision-making statement which
helps us to take a decision on the based on the condition.
 The block of code inside the if statement will be executed only when the boolean
expression is satisfy.
 Else rest of the code will run. Flowchart
Syntax:
if(boolean_expression)
{
// execute only expression true
}
Example:
x=20
y=24
if(x<y)
{
print(x,“is a smaller number”);
}
ii)If-else statement:An if-else statement is the if statement followed by an else
statement.
In if-else statement, else statement will be executed when the Boolean expression will false
Syntax:
if(boolean_expression)
{ Flowchart
// execute when expression true
}
else
{
// execute when expression false
}
Ex: Check which is the smaller number
between x and y
x=20
y=24
if(x<y)
{
print(x,“is a smaller number”)
}
Else
{
print(y,“is a smaller number”)
}
iii)else if Ladder Statement: This is basically a “multi-way” decision statement.
 This is used when we must choose among many alternatives.
 The expressions are evaluated in order (i.e. top to bottom).

Syntax:
if(expression1) Flowchart
{
statement1;
}
else if(expression2)
{
statement2;
}
else if(expression3)
{
statement3
}
else
default statement5
Example: Check the grade of the student based on his marks
int marks=83;
if(marks>85)
{
print(“Distinction“)
}
else if(marks>60)
{
print(“First class“)
}
else if(marks>40)
{
print(“Second class“)
}
Else
{
print("Fail“)
}
Output: First class
 Iv)nested if Statement An if-else statement within another if-
else statement is called nested if statement.
 Syntax:
 if(expr1)
 { Flowchart
 if(expr2)
 statement1
 else
 statement2
 }
 else
 {
 if(expr3)
 statement3
 else
 statement4
 }
Example: Check which is the largest value among a,b and c using nested if statement
Int a=7,b=8,c=6
if (a > b)
{
if (a > c)
{
cout<<"largest value=“<<a;
}
else
{
cout<<"largest value=“<<c;
}
}
else
{
if (b > c)
{
cout<<"largest value =“<< b;
}
else
{
cout<<"largest value =“<< c;
}
}
Output: Largest Value is: 8
 Using `ifelse` for Element-wise Checks:performs conditional
operations on each element of a vector
 ➢ returns corresponding values based on whether condition is TRUE
or FALSE.
 .Syntax:
 ifelse(test, yes, no)
 Where,
 test: A logical vector or expression that specifies the condition
to be tested.
 yes: The value to be returned when the condition is TRUE.
 no: The value to be returned when the condition is FALSE.
 Example:
 # Create a numeric vector
 grades <- c(85, 92, 78, 60, 75)
 # Use ifelse to categorize grades as "Pass" or "Fail"
 pass_fail <- ifelse(grades >= 70, "Pass", "Fail")
 # Display the result
 pass_fail
 Output: "Pass" "Pass" "Pass" "Fail" "Pass"
V)The switch-statement: This is basically a “multi-way”
decision-statement.
• This is used when we must choose among many alternatives.
Syntax: Flowchart:
switch(expression,
case1, result1,
case2, result2,
...,...
default)
 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
 A)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)
 }
 Nesting for Loops: Nesting for loops involves placing one
for loop inside another.
 This allows you to create complex iteration patterns where
you iterate over elements of multiple data structures.
Example:
 for (i in 1:3)
 {
 for (j in 1:3)
 {
 product <- i * j
 cat(product, "\t")
 }
 cat("\n")
 }
 while Loop:
 Syntax:
 while(expression)
 {
 statement1;
 }
 • A while loop statement can be used to execute a set of
statements repeatedly as long as a given condition is true.
 • Firstly, the expression is evaluated to true or false.
 • If the expression is evaluated to false, the control comes out
of the loop without executing the body of the loop.
 • If the expression is evaluated to true, the body of the loop
(i.e. statement1) is executed.
 • After executing the body of the loop, control goes back to
the beginning of the while statement.
 i <- 1
 # Initialize a variable
 while (i <= 3)
{
 cat("Welcome to R \n")
 i <- i + 1
}
 Output:
 Welcome to R
 Welcome to R
 Welcome to R
 Example: Program to Create Identity Matrices
 # Specify the size of the identity matrix (e.g., n = 4)
 n <- 4
 row <- 1
 identity_matrix <- matrix(0, nrow = n, ncol = n)
 # Use a while loop to populate the matrix
 while (row <= n)
{
 identity_matrix[row, row] <- 1
 row <- row + 1
}
 # Print the identity matrix
 print(identity_matrix)
 Output:
 [,1] [,2] [,3] [,4]
 [1,] 1 0 0 0
[2,] 0 1 0 o
 [3,] 0 0 1 0
 [4,] 0 0 0 1
 Implicit Looping with apply(): The apply function is used
for applying a function to subsets of a data structure, such as
rows or columns of a matrix.
 • It allows you to avoid writing explicit loops and can simplify
your code.
 Syntax: apply(X, MARGIN, FUN)
 Where
 X: The data structure (matrix, data-frame, or array) to
apply the function to.
 MARGIN: Specifies whether the function should be
applied to rows (1) or columns (2) of the data structure.
 FUN: The function to apply to each subset.
 # Create a sample matrix of exam scores
 scores_matrix <- matrix(c(60, 70, 80, 90, 60, 70, 80, 90, 60, 70, 80,
90), nrow = 4 )
 # Use apply to calculate the mean score for each student (across
exams)
 mean_scores <- apply(scores_matrix, 1, mean)
 # Print the mean scores
 cat("Mean Scores:")
 print(mean_scores)
 Output:
 Mean Scores:
 60 70 80 90
WRITING FUNCTIONS
 Function Creation: A function is a block of code to perform a specific task.
 Function is defined using the `function` keyword.
 This can take one or more arguments.
 This can also return values using the `return` statement.
 Syntax: function_name <- function(arg1, arg2, ...)
 {
 # Function body
 # Perform some operations using arg1, arg2, and other arguments
 # Optionally, return a result using 'return' statement
 }
 Example:
 square <- function(x)
{
 result <- x * x
 return(result)
}

 result <- square(5) //call the function


 cat("The square of 5 is:", result)
 Output:
 The square of 5 is: 25
 Function to print the Fibonacci sequence up to 150.
 fibo1 <- function()
 {
 a <- 1
 b <- 1
 cat(a, ", ", b, ", ", sep = "")
 while (b <= 150)
 {
 temp <- a +b
 a <- b
 b <- temp
 if (b <= 150)
 {
 cat(b, ", ", sep = "")
 }
 }
 }
 fibo1() # Call the function to print the Fibonacci sequence up to 150
 Output: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
 Passing arguments
 Example: Function to print area of circle
 [Link] <-function(r)
{
 area <- pi*r^2
 return (area)
}
 [Link](7)

 Output:
 Using return: return is used to specify what value should be returned as the
result of the function
 • This allows you to pass a value or an object back to the calling code.

 Example:
 add_numbers <- function(x, y)
 {
 result <- x + y
 return(result)
 }
 # Call the function and store the result in a variable
 sum_result <- add_numbers(5, 3)
 # Print the result
 cat("The sum is:", sum_result, "\n")
 Output:
 The sum is:8
 Arguments
 A)Lazy Evaluation: Lazy evaluation means expressions
are evaluated only when needed.
 The evaluation of function-arguments is deferred until
they are actually needed.
 The arguments are not evaluated immediately when a
function is called but are evaluated when they are
accessed within the function.
 This can help optimize performance and save
computational resources.
 • 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
 # Call the function with the variables
 lazy_example(x, y)
 Output:
 Inside the function
 a = 10
 b = 20
 Performing some operations...
 Operations completed
 [1] 30
 B)Setting Defaults: You can provide predefined values for some or all of the
arguments in a function.
 Useful for providing a default behavior if user doesn't specify a value for
arguments.
 Syntax:
 function_name <- function(arg1 = default_value1, arg2 = default_value2, ...)
 {
 # Function body
 # Use arg1, arg2, and other arguments
 }
 ‘Where
 `arg1`, `arg2`, etc.: These are the function-arguments for which you
want to set default values.
 `default_value1`, `default_value2`, etc.: These are the values you assign
as defaults for the respective arguments.
 Example: Function to calculate the area of a rectangle
 calculate_rectangle_area <- function(width = 2, height = 3)
 {
 area <- width * height
 return(area)
 }
 # Call the function without specifying width and height
 default_area <- calculate_rectangle_area()
 # Call the function with custom width and height
 custom_area <- calculate_rectangle_area(width = 5, height = 4)
 cat("Default Area:", default_area, "\n")
 cat("Custom Area:", custom_area, "\n")
 Output:
Checking for Missing Arguments

 missing() is used to check if an argument was provided


when calling a function.
 It returns `TRUE` if the argument is missing (not
provided) and `FALSE` if the argument is provided.
 • Syntax:
 missing(argument_name)
 Where.
 `argument_name`: This is the name of the
argument you want to check
 Example: Function to check if an argument is missing
 check_argument <- function(x)
 {
 if (missing(x))
 {
 cat("The argument 'x' is missing.\n")
 }
 else
 {
 cat("The argument 'x' is provided with a value of", x, "\n")
 }
 }
 # Call the function without providing 'x'
 check_argument()
 # Call the function with 'x'
 check_argument(42)
 Output:
 The argument 'x' is missing
 The argument 'x' is provided with a value of 42
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
 Internally Defined Helper Functions:
 These functions are also known as user-defined functions.
 • They are defined by programmer according to their requirement.
 • They are used to perform a specific task or operation.
 • They enhance code organization, reusability, and readability.
 • Example: Internally defined helper function to calculate the square of
a number
 square <- function(x)
 {
 result <- x * x return(result)
 }
 num <- 5
 squared_num <- square(num)
 cat("The square of", num, "is:", squared_num, "\n")
 Output:
 The square of 5 is: 25
 Disposable Functions: These functions are created
and used for a specific, one-time task.
 They are not intended for reuse or long-term use.
 They are often employed to perform a single, temporary
operation.
 They are discarded after use.
 Example: A disposable function to calculate the area of a
rectangle once
 calculate_rectangle_area <- function(length, width)
 {
 area <- length * width
 cat("The area of the rectangle is:", area, "\n")
 }
 # Use the disposable function to calculate the area of a
specific rectangle
 calculate_rectangle_area(5, 3)
 Output:
 The area of the rectangle is: 15
 Recursive Functions: These functions call themselves
within their own definition.
 • They solve problems by breaking them down into
smaller, similar sub problems.
 • They consist of two parts: a base case and a recursive
case.
 • The base case defines the condition under which the
recursion stops. The recursive case defines how the
problem is divided into smaller sub problems and
solved recursively.
 Example: Recursive function to calculate the nth Fibonacci number
 myfibrec <- function(n)
 {
 if (n == 1 || n == 2)
 {
 return(1) # Base cases: Fibonacci of 1st and 2nd numbers are both 1 }
 else
 {
 return(myfibrec(n - 1) + myfibrec(n - 2)) # Recursive case
 }
 }
 # Example:
 Calculate the 5th Fibonacci number
 n <- 5
 result <- myfibrec(n)
 cat("The", n, "th Fibonacci number is:", result, "\n")
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
 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
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
 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
 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))
 }
 Output:
 5
 2.5
 1.25
 Error in 5/I
 : non numeric argument to binary operator 1
 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'})
 Timing and visibility:
 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 [Link] NZDT"
 The [Link] command makes R pause for a specified
amount of time, in seconds, before continuing.
 Syntax:
 Starttime <-[Link]()
 {
 Func()
 }
 Endtime<-[Link]()
 Example: Sleep_func <-function()
{
 [Link](5)
}
 Starttime<-[Link]()
{
 Sleep_func()
}
 Endtime<-[Link]()
 Print(Endtime-Starttime)
 Output: 5.008 sec
 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.
 • 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.
 Example: 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.
 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

You might also like