Unit 2 R
Unit 2 R
UNIT-2
1. readline() Function:
Definition: The readline() function reads a single line of input from the console and returns it as
a character string.
prompt: A string that will be displayed in the console to ask for input.
Definition: Since readline() captures input as a string, we can convert the input into numeric or
integer values using as.numeric() or as.integer() functions.
2. scan() Function
Definition: The scan() function is a more flexible way to read multiple numbers or
values from the console or a file. The default behavior is to read numeric input, but it can
be customized to read text as well.
1. print() Function:
Definition: The print() function is used to display data or results in the R console.
It prints one object at a time and automatically converts data to a human-readable
format.
Syntax: print(x)
Example:
x <- 42
print(x)
2. cat() Function
Definition: The cat() function is used to concatenate and output objects. It allows for
more flexible and formatted output compared to print(), but it does not return the
structure or index like print() does.
Syntax: cat(..., file = "", sep = " ", fill = FALSE, labels = NULL, append = FALSE)
...: Objects to be concatenated.
sep: The separator between objects (default is a space).
file: The name of the file to write output to (default is an empty string, meaning the
console).
Example:
name <- "John"
age <- 25
cat("Hello", name, ", you are", age, "years old.\n")
1. message() Function
Definition: The message() function is used to print warning or error messages to the console.
It is mainly used for displaying information or warnings that do not interrupt the execution of
the program.
Syntax: message(x, domain = NULL, appendLF = TRUE)
x: The object or string to display as a message.
appendLF: Whether to append a newline (TRUE by default).
Example:
if (age < 18) {
message("You are underage.")
2. paste() Function
Definition: The paste() function is used to concatenate objects or values together into a
single string. It is often used in conjunction with cat() or print() to form formatted output.
Syntax: paste(..., sep = " ", collapse = NULL)
...: The objects to concatenate.
sep: The separator between objects (default is a space).
collapse: Optional parameter to collapse the result into a single string.
Example:
a <- "Hello"
b <- "World"
result <- paste(a, b, sep = ", ")
print(result)
print(): Used for basic output, automatically formats the data and shows the index of
vector elements.
cat(): Used for concatenating and displaying formatted output, without showing the
vector index.
message(): Used for displaying warning or informational messages.
paste(): Used for combining and formatting strings before outputting.
Writing to Files: You can use write(), write.table(), or write.csv() to output results to
files for persistent storage.
Each of these functions serves different purposes based on how the user wants to display or store
the output.
1. if Statement in R
Definition: The if statement in R is a control structure that allows you to execute a block of code
only if a specified condition evaluates to TRUE. If the condition is FALSE, the code inside the if
block is skipped.
Key Points:
Syntax:
if (condition) {
# code to execute if the condition is TRUE
}
Example:
x <- 10
if (x > 5) {
print("x is greater than 5")
}
2. if...else Statement in R
The if...else statement in R is used to execute a block of code when a condition is true, and
another block of code when the condition is false. It allows for decision-making by evaluating a
logical condition and choosing between two alternatives.
Key Points:
Single Condition Evaluation: The if statement checks a condition, and if it's true, the
code inside the if block is executed.
Alternative Block: If the condition is false, the code inside the else block is executed.
Control Flow: Helps in branching the program flow based on conditions.
Syntax:
if (condition) {
# code to execute if condition is true
} else {
# code to execute if condition is false
}
Example:
x <- 10
if (x > 5) {
print("x is greater than 5")
} else {
print("x is less than or equal to 5")
}
3. if...else if...else Statement:
The if...else if...else statement is a conditional structure in R that allows you to test multiple
conditions sequentially. It evaluates the conditions in the order they are written, and as soon
as a condition evaluates to TRUE, the corresponding block of code is executed. If none of the
conditions are TRUE, the block in the else section (if provided) is executed.
Syntax: if (condition1) {
# Code to execute if condition1 is TRUE
} else if (condition2) {
# Code to execute if condition2 is TRUE
} else {
# Code to execute if none of the above conditions are TRUE
}
Example:
x <- 15
if (x > 20) {
print("x is greater than 20")
} else if (x == 15) {
print("x is equal to 15")
} else {
print("x is less than 20")
}
4. switch Statement:
The switch statement in R is used for multi-way branching. It evaluates an expression
and executes the corresponding block of code based on the value of the expression.
The value returned by switch() depends on the matched case. If no matching case is
found, an optional default case can be executed.
Key Points:
switch() is used when there are multiple possible values for an expression.
It is useful for replacing multiple if...else if conditions with a cleaner, more readable
structure.
The expression can either be numeric (position-based) or character (name-based).
Syntax:
switch(expression,
case1 = value1,
case2 = value2,
...,
default_value)
Examples: Switch with a Default Case:
result <- switch("grape",
"orange" = "This is an orange",
"apple" = "This is an apple",
"banana" = "This is a banana",
"Unknown fruit")
print(result)
Looping Statements in R
1. for Loop: The for loop in R is used to iterate over a sequence (such as a vector, list, or any
iterable object) and execute a block of code for each element in that sequence.
Syntax:
for (variable in sequence) {
# Code to execute in each iteration
}
Example:
# Example: Printing numbers from 1 to 5
for (i in 1:5) {
print(i)
}
2. while Loop: The while loop in R executes a block of code as long as the specified condition
remains TRUE. It evaluates the condition before executing the loop body.
Syntax:
while (condition) {
# Code to execute as long as the condition is true
}
Example:
# Example: Print numbers from 1 to 5 using a while loop
x <- 1
while (x <= 5) {
print(x)
x <- x + 1
}
3. repeat Loop: The repeat loop in R allows you to repeat a block of code indefinitely until you
explicitly exit the loop using a break statement. It does not check any condition before
starting the loop, so the exit condition must be specified within the loop.
Syntax:
repeat {
# Code to execute repeatedly
if (condition) {
break # Exit the loop if the condition is met
}
}
Example:
# Example: Printing numbers from 1 to 5 using repeat loop
x <- 1
repeat {
print(x)
x <- x + 1
if (x > 5) {
break # Exit loop when x is greater than 5
}
}
2. next: Skips to the next iteration. The next statement in R is used to skip the current iteration
and proceed to the next iteration in the loop. When next is encountered, the remaining code
in the current iteration is ignored, and the loop moves to the next iteration.
Syntax: next
Example:
# Example: Skipping the iteration when i equals 3
for (i in 1:5) {
if (i == 3) {
next # Skip the rest of the code when i equals 3
}
print(i)
}
FUNCTIONS IN R
A function is a block of code (set of statements) to perform a specific task. The function gets
executed only when a function is called. Parameter/argument is the data(s) the function receives
SESHADRIPURAM COLLEGE TUMKUR Page 7
Unit-2 Statistical Computing & R Programming
to perform specific tasks. A function may or may not return a value. The major advantages of
functions include code reusability and easy debugging of program.
Functions can be built in R functions as well we can define our own user defined functions.
The user defined functions need to be defined first before they are called.
A function in R is a block of organized, reusable code that performs a specific task. Functions
are used to reduce code redundancy, increase reusability, and make the code more modular and
readable. In R, functions can take arguments (input values) and return values as output.
Syntax:
This function takes two numbers as inputs and returns their sum.
# Defining a function to add two numbers
add_numbers <- function(a, b) {
sum <- a + b
return(sum)
}
# Calling the function
result <- add_numbers(5, 3)
print(result) # Output: 8
Key Factors:
Useful when you don’t know in advance how many arguments the function will receive.
Allows flexibility for functions to accept an arbitrary number of arguments.
Often used in combination with functions that pass arguments to other functions, like
plot(), apply(), etc.
Syntax:
print(result1)
print(result2)
Syntax:
Example:
greet <- function(name) {
if (missing(name)) {
print("Hello, Guest!")
} else {
print(paste("Hello,", name))
}
}
# Calling function without argument
greet() # Outputs "Hello, Guest!"
# Calling function with an argument
greet("R-programmer") # Outputs "Hello, R-programmer "
FUNCTION AS ARGUMENT
Definition: In R, you can pass a function as an argument to another function. This is a powerful
feature, especially in cases like functionals, where a function needs to apply another function
over a list, vector, or matrix.
Key Factors:
Functions like apply(), lapply(), sapply(), and Reduce() make use of functions as
arguments.
Promotes modularity and code reuse.
func(arg)
}
Example:
apply_function <- function(func, x) {
func(x)
}
RECURSION
Definition: Recursion in R is a programming technique where a function calls itself to solve
smaller instances of the same problem. This technique is used when a problem can be divided
into simpler, smaller sub-problems of the same type.
1. Base Case: The condition under which the function stops calling itself (the terminating
case).
2. Recursive Case: The part of the function where it calls itself with a modified argument
to approach the base case.
Base Case: Ensures that the recursion terminates and does not result in infinite loops.
Recursive Case: Makes progress toward the base case in each recursive call.
Memory Usage: Recursion can be memory-intensive, as each recursive call adds a new
frame to the function call stack.
Efficiency: Some recursive algorithms may not be as efficient as their iterative
counterparts, depending on the problem and implementation.
Simple Problem Breakdown: Recursion is useful when the problem can be broken
down into smaller, repetitive sub-problems.
Syntax of Recursion in R
function_name <- function(parameters) {
if (base_case_condition) {
return(base_case_value)
} else {
return(function_name(modified_parameters)) # Recursive call
}
}
The factorial of a number n is the product of all positive integers up to n (i.e., n * (n-1) * (n-2) *
... * 1). The base case is factorial(0) = 1.
Code:
# Example usage:
factorial_recursive(5)
The Fibonacci sequence is a series where each number is the sum of the two preceding ones. The
base cases are fib(0) = 0 and fib(1) = 1.
Code:
# Example usage:
fibonacci_recursive(6)
EXCEPTIONS IN R
Definition: In R programming, exceptions are unusual or erroneous conditions that disrupt the
normal flow of a program. Exception handling allows the program to handle these conditions
gracefully, rather than terminating unexpectedly. The most common exceptions in R include
missing values (NA), invalid operations, or errors during runtime.
R provides various methods for dealing with exceptions, such as error handling and recovery
mechanisms like try(), tryCatch(), and stop(). These functions allow users to manage errors in a
way that does not interrupt the execution of an entire program.
1. try(): try() executes an expression and catches any error without stopping the program.
Example of try():
2. tryCatch(): tryCatch() is a more robust function for exception handling, allowing for
specific handling of errors, warnings, and even messages.
tryCatch(expression,
error = function(e) { ... },
warning = function(w) { ... },
finally = { ... })
Example of tryCatch():
3. stop(), warning(), and message(): These functions allow you to generate exceptions
intentionally:
Example of stop():
x <- -1
if (x < 0) {
stop("Negative values are not allowed.")
}
Example of warning():
x <- -1
if (x < 0) {
warning("This is a negative value.")
}
Example of message():
message("This is an informational message.")
Output:
For stop(): The program will halt, displaying "Negative values are not allowed."
For warning(): The program will display a warning, but it will continue running.
For message(): The message will be shown without interrupting the execution.
Key Takeaways:
try(): Catches errors without stopping the program, useful for soft error handling.
tryCatch(): Provides more control over error, warning, and finally blocks.
stop(): Raises an error, halting execution.
warning(): Issues a warning without stopping execution.
message(): Sends a message without affecting the flow of the program.
1. Sys.time(): The Sys.time() function in R returns the current date and time of the system in
which R is running.
Key Factors:
Returns the system's current date and time.
The result is a POSIXct object, which can be easily formatted or manipulated.
Syntax: Sys.time()
Example:
current_time <- Sys.time()
print(current_time)
2. Sys.sleep(n): The Sys.sleep(n) function pauses the execution of R code for n seconds.
Key Factors:
Useful for adding delays in scripts (e.g., waiting for resources, rate-limiting API
calls).
n is the number of seconds to pause. It can be a decimal value if you want to wait
for fractions of a second.
Syntax: Sys.sleep(n)
Example:
print("Start")
Sys.sleep(3) # Pauses for 3 seconds
print("End")
3. system.time(expr): The system.time() function measures the amount of time taken to evaluate
an expression or piece of code.
Key Factors:
Syntax: system.time(expr)
Example
system.time({
sum <- 0
for (i in 1:1000000) {
sum <- sum + i
}
print(sum)
})
PROGRESS BAR IN R
Definition: A progress bar in R is a visual tool used to indicate the progress of a long-running
task or operation. It provides a visual feedback of the completion status of a task, helping users
understand how much of the process has been completed and how much is left. It is particularly
useful in loops or iterative operations.
Key Factors:
Indication of Progress: Helps monitor the progress of tasks that may take time to
complete.
User Feedback: Provides real-time feedback to the user about ongoing operations.
Customizable: Can be customized with different styles, lengths, and messages.
Libraries for Progress Bars: In R, there are several ways to implement progress bars,
with packages like utils (base R) or progress (third-party package) offering flexible
solutions.
In R, the txtProgressBar function from the utils package is used to create a progress bar.
# Syntax:
pb <- txtProgressBar(min = 0, max = 100, style = 3)
# Start with min, max values and style for the progress bar.
for(i in 1:100) {
Sys.sleep(0.1) # Simulate some work with delay
setTxtProgressBar(pb, i) # Update progress bar
}
A more advanced progress bar is available through the progress package. This allows more
customization and a cleaner interface.
library(progress)
Examples:
for(i in 1:10) {
Sys.sleep(0.2) # Simulate time-consuming work
setTxtProgressBar(pb, i) # Update the progress bar
}
pb <- progress_bar$new(
format = " processing [:bar] :percent done in :elapsed",
total = 50, clear = FALSE, width = 50
)
for (i in 1:50) {
Sys.sleep(0.1) # Simulate a task
pb$tick() # Update the progress bar
}
Key Parameters:
Sample questions
1. Write a R code to find the factorial of a number using recursion.
2. Explain control structures in R with examples.
3. Explain looping statements in R with examples.
4. Explain Functions in R with examples.
5. Explain R Function With Dots Arguments with examples.
6. Explain Missing Arguments with Missing() with examples.
7. Explain Function as Argument with examples.
8. Explain Recursion with examples.
9. Explain Exceptions in R with examples.
10. Explain Timing In R (Sys.Time(), Sys.Sleep(N), System.Time())with examples.
11. Explain Progress Bar in R with examples.