Unit 2 R Programming
Unit 2 R Programming
Unit 2 R Programming
Unit 2
R Programming
In R programming, reading and writing files involves various functions that allow you to interact
with files on your computer. Here’s a detailed explanation along with examples for reading and
writing files in R.
Reading Files in R
Reading Text Files
1. Reading from Text Files (CSV, TXT, etc.):
o Use [Link]() or [Link]() for reading tabular data from CSV files.
o Use readLines() for reading lines from a text file.
Example:
# Reading from a CSV file
data <- [Link]("[Link]")
# Reading from a text file
lines <- readLines("[Link]")
Writing Files in R
Writing Text Files
1. Writing to Text Files:
o Use [Link]() or [Link]() for writing data frames to CSV files.
o Use writeLines() for writing lines of text to a text file.
Example:
# Writing to a CSV file
[Link](data, "[Link]")
# Writing lines to a text file
lines <- c("Line 1", "Line 2", "Line 3")
writeLines(lines, "[Link]")
1
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
These functions provide robust capabilities for handling various file formats and are
essential for data import/export tasks in R programming. Adjust these examples based on your
specific file formats and requirements.
Input Statements in R
1. Reading Input from the User:
o Use readline() to take a single-line input from the user.
o For numeric input, you can convert the string input to a numeric type using
[Link]().
Example:
# Reading the first number from the user
num1 <- [Link](readline(prompt = "Enter the first number: "))
# Reading the second number from the user
num2 <- [Link](readline(prompt = "Enter the second number: "))
# Adding the two numbers
sum <- num1 + num2
# Displaying the result
cat("The sum of", num1, "and", num2, "is:", sum, "\n")
Output
Enter the first number: 10
Enter the second number: 10
2
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Example:
# Reading the first number from the user
num1 <- [Link](readline(prompt = "Enter the first number: "))
# Reading the second number from the user
num2 <- [Link](readline(prompt = "Enter the second number: "))
# Adding the two numbers
sum <- num1 + num2
# Displaying the result
cat("The sum of", num1, "and", num2, "is:", sum, "\n")
Output
Enter the first number: 10
3
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Program
#reading two numbers from the user
numbers <- scan(what=numeric(), nmax=2)
#adding the two numbers
result <-sum(numbers)
#displaying the result
cat(“The sum is:”,result)
Output
1: 10
2: 20
The sum is: 30
Example:
# Program to read numeric values from a file using scan()
# Specify the file path (replace with your actual file path)
print(values)
4
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
# Perform some basic operations on the data
Output
[1] 5 10 15 20 25 30 35 40 45 50 55 60
Minimum value: 5
Maximum value: 60
5
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Example:
1. print() Function:
The print() function is the most basic way to display the value of an object in R. It automatically
formats the output and is typically used to print the value of variables, results of calculations, or
objects like vectors, data frames, etc.
Example:
# Define a variable
x <- 42
# Use print() to display the value of the variable
print(x)
# You can also directly print the result of an expression
print(x + 10)
Output
2. cat() Function
The cat() function is used for concatenating and printing objects in a more flexible and user-
defined format. Unlike print(), cat() does not add quotes around strings and does not display
the position index [1].
Example
# Define some variables
name <- "Alice"
age <- 25
# Use cat() to output a formatted string
cat("Name:", name, "\nAge:", age, "\n")
Output
3. message() Function
The message() function is used to display diagnostic messages or warnings to the user. It is
similar to cat(), but it sends output to a different output stream, allowing messages to be
suppressed or redirected more easily.
6
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Example:
# Use message() to display a diagnostic message
message("This is a warning message.")
Output
Example
# Define variables
name <- "Bob"
score <- 85
# Use print() to show a simple output
print(score)
# Use cat() to show a formatted message
cat("Student:", name, "- Score:", score, "\n")
# Use message() to show a warning or informational message
if (score < 50)
{
message("Warning: Score is below passing threshold.")
}
else
{
message("Congratulations! You passed.")
}
Output
7
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Conditional Statements
Conditional statements allow a program to make decisions and execute different code blocks
based on certain conditions. Here’s a detailed explanation of various conditional statements with
if Statement:
The if statement in R evaluates a condition and executes a block of code if the condition is true.
The general syntax is
if (condition)
{
# Code to execute if condition is true
}
Examples:
age <- 18
if (age >= 18)
{
Output
In this example, since age is 18, the condition age >= 18 is true, so "You are eligible
to vote." is printed.
2. if-else Statement
The if-else statement allows you to provide an alternative block of code that executes if the
condition is false.
Syntax:
if (condition)
{
# Code to execute if condition is true
}
else
{
# Code to execute if condition is false
}
8
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Example
age <- 16
if (age >= 18)
{
print("You are eligible to vote.")
}
else
{
print("You are not eligible to vote.")
}
Output
Syntax:
if (condition1)
{
# Code to execute if condition1 is true
}
else if (condition2)
{
# Code to execute if condition2 is true
}
else if (condition3)
{
# Code to execute if condition3 is true
}
else
{
# Code to execute if none of the conditions are true
}
9
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Example:
# Input: student marks
marks <- 78
# Determine grade
if (marks >= 90)
{
grade <- "A"
} else if (marks >= 80)
{
grade <- "B"
} else if (marks >= 70)
{
grade <- "C"
} else if (marks >= 60)
{
grade <- "D"
} else
{
grade <- "F"
}
# Output grade
print(paste("Grade:", grade))Output
Output
4. switch Statement
The switch statement in R evaluates an expression and compares it against a list of possible
values, executing the corresponding block of code.
Syntax:
switch(expression,
case1 = { # Code for case1 },
case2 = { # Code for case2 },
case3 = { # Code for case3 },
default = { # Code for default case }
)
10
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Example
val1 = 6
val2 = 7
val3 = "s"
result = switch(
val3,
"a"= cat("Addition =", val1 + val2),
"d"= cat("Subtraction =", val1 - val2),
"r"= cat("Division = ", val1 / val2),
"s"= cat("Multiplication =", val1 * val2),
"m"= cat("Modulus =", val1 %% val2),
"p"= cat("Power =", val1 ^ val2)
)
print(result)
Output
Looping statements
In R programming, looping statements are used to execute a block of code repeatedly based on
certain conditions. The primary looping constructs in R are:
1. for loop: Used to iterate over a sequence (like a vector or list) and execute a block of
code for each element.
2. while loop: Repeats a block of code as long as a specified condition is true.
3. repeat loop: Repeats a block of code indefinitely until a break statement is encountered.
1. for Loop
Definition: The for loop iterates over a sequence (such as a vector or list) and executes a block
of code for each element in the sequence.
Syntax
for (variable in sequence)
{
# Code to be executed
}
11
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Example
# Using a for loop to print numbers from 1 to 5
for (i in 1:5)
{
print(i)
}
Output
Explanation:
variable is i, which takes on each value in the sequence 1:5 (i.e., 1, 2, 3, 4, 5).
The print(i) statement is executed for each value of i, printing the numbers 1 through 5.
2. while Loop
Definition: The while loop repeatedly executes a block of code as long as a specified condition
remains true.
Syntax:
while (condition)
{
# Code to be executed
# Update or modify the condition variable
}
Example
# Initializing the counter
i <- 1
# Using a while loop to print numbers from 1 to 5
while (i <= 5)
{
print(i)
i <- i + 1
}
12
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Output
3. repeat Loop
Definition: The repeat loop executes a block of code indefinitely until a break statement is
encountered.
Syntax:
repeat
{
# Code to be executed
# Use a break statement to exit the loop
}
Example
# Using a repeat loop to print numbers from 1 to 5
i <- 1 # Initialize the counter
repeat
{
print(i)
i <- i + 1 # Increment the counter
if (i > 5)
{ # Exit the loop if i is greater than 5
break
}
}
Output
13
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Explanation:
The repeat loop continues indefinitely until the break statement is executed.
print(i) prints the current value of i.
i <- i + 1 updates the value of i.
The if statement checks if i is greater than 5 and, if true, exits the loop with break.
Functions
Definition: A function in R is a block of code that performs a specific task and can be reused
multiple times within a program. Functions take inputs (called arguments), process them, and
return an output.
Syntax:
Defining a function
function_name <- function(arg1, arg2, ...)
{
# Code to execute
# Return value
}
Explanation:
function_name is the name you give to the function.
arg1, arg2, ... are the parameters or arguments passed to the function.
The code block is the set of instructions that define what the function does.
The return(value) statement (optional) specifies what the function should return. If not
explicitly used, the function returns the result of the last evaluated expression.
Example:
# Define a function to calculate the square of a number
square_number <- function(x)
{
result <- x^2 # Calculate the square of x
return(result) # Return the result
}
# Call the function with an argument
square_of_4 <- square_number(4)
# Print the result
print(paste("The square of 4 is", square_of_4))
14
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Output
Explanation:
1. Function Definition:
o square_number is the name of the function.
o function(x) specifies that the function takes one argument x.
o Inside the function, result <- x^2 calculates the square of x.
o return(result) returns the computed square.
2. Function Call:
o square_number(4) calls the function with 4 as the argument.
o The function computes the square of 4 and returns 16.
Calling a Function
Definition: Calling a function involves using the function name and providing the necessary
arguments to execute the function. This triggers the code within the function and returns the
result.
Syntax:
result <- function_name(argument1, argument2, ...)
Explanation:
function_name is the name of the function you want to call.
argument1, argument2, ... are the values you pass to the function’s parameters.
result stores the value returned by the function.
Example
# Define a function to calculate the area of a rectangle
calculate_area <- function(length, width)
{
area <- length * width # Calculate the area
return(area) # Return the calculated area
}
# Call the function with specific arguments
rectangle_area <- calculate_area(5, 10)
# Print the result
print(paste("The area of the rectangle is", rectangle_area))
15
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Output
Types of functions
There are two types of functions
Built in functions
User defined functions
Built in functions
Definition: Built-in functions in R are pre-defined functions that come with R and its packages.
They perform common tasks and operations, and you can use them directly without needing to
define them yourself.
Syntax
function_name(argument1, argument2, ...)
Syntax:
mean(x, [Link] = FALSE)
x is a numeric vector.
[Link] is a logical value indicating whether to remove NA values before computation
(default is FALSE).
Example:
# Calculate the mean of a numeric vector
numbers <- c(10, 20, 30, 40, 50)
average <- mean(numbers)
print(paste("The average is", average))
Output
16
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
2. sum()
Definition: The sum() function calculates the total sum of a numeric vector.
Syntax:
sum()
Example
# Calculate the sum of a numeric vector
numbers <- c(5, 15, 25, 35, 45)
total_sum <- sum(numbers)
print(paste("The total sum is", total_sum))
Output
3. length()
Definition: The length() function returns the number of elements in a vector or list.
Syntax:
length(x)
x is a vector or list.
Example
# Get the length of a numeric vector
numbers <- c(1, 2, 3, 4, 5)
vector_length <- length(numbers)
print(paste("The length of the vector is", vector_length))
Output
Explanation:
length(numbers) returns the number of elements in numbers, which is 5.
4. sd()
Definition: The sd() function calculates the standard deviation of a numeric vector.
Syntax:
sd(x, [Link] = FALSE)
17
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Explanation
x is a numeric vector.
[Link] is a logical value indicating whether to remove NA values before computation
(default is FALSE).
Example
# Calculate the standard deviation of a numeric vector
numbers <- c(1, 2, 3, 4, 5)
standard_deviation <- sd(numbers)
print(paste("The standard deviation is", standard_deviation))
Output
5. round()
Definition: The round() function rounds numbers to a specified number of decimal places.
Syntax:
round(x, digits = 0)
Explanation
x is a numeric vector.
digits specifies the number of decimal places to round to (default is 0).
Example:
# Round numbers to 2 decimal places
values <- c(3.14159, 2.71828, 1.61803)
rounded_values <- round(values, 2)
print(paste("Rounded values are", toString(rounded_values)))
Output
Explanation:
round(values, 2) rounds each element in values to 2 decimal places: 3.14, 2.72, 1.62.
18
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Explanation:
calculate_triangle_area is the name of the function.
It takes two parameters: base and height.
Inside the function, area <- 0.5 * base * height computes the area of the triangle.
return(area) returns the computed area.
Unit 2 R Programming
Full Example
# Define a function to calculate the area of a triangle
calculate_triangle_area <- function(base, height)
{
area <- 0.5 * base * height # Calculate the area
return(area) # Return the result
}
# Call the function with specific arguments
triangle_area <- calculate_triangle_area(10, 5)
# Print the result
print(paste("The area of the triangle is", triangle_area))
Output
Variable Scoping:
Definition: Variable scoping in R refers to the rules that determine the visibility and lifetime of
variables in different parts of your code. It defines where a variable can be accessed and
modified.
In R, variable scoping is influenced by the environment in which a variable is defined and
used. Here’s an explanation with an example:
Example
# Define a global variable
global_var <- 10
# Function that uses the global variable
print_global <- function()
{
print(paste("Global variable value is:", global_var))
}
# Call the function
print_global()
20
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Output
2. Local Scope:
o Variables defined inside a function are local to that function. They are only
accessible within the function and are not visible outside of it.
Example:
# Define a function with a local variable
local_function <- function()
{
local_var <- 20 # Local variable
print(paste("Local variable value inside function is:", local_var))
}
# Call the function
local_function()
# Try to access the local variable outside the function
print(local_var) # This will produce an error
Output
3. Lexical Scoping:
o R uses lexical scoping, meaning that the function’s environment is determined
by where the function is defined, not where it is called. This allows functions
to access variables from their environment when they were created.
Example:
# Define an outer function
outer_function <- function(x)
{
# Define a variable in the outer function
outer_var <- x
# Define an inner function
inner_function <- function(y)
{
# Define a variable in the inner function
inner_var <- y
# Access and use variables from both inner and outer scopes
21
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
result <- outer_var + inner_var
return(result)
}
# Call the inner function
inner_function(5)
}
# Call the outer function with an argument
result <- outer_function(10)
# Print the result
print(paste("The result is", result))
Output
Example:
# Define a variable in the global environment
global_variable <- "I am a global variable"
{
local_variable <- "I am a local variable"
print(global_variable) # Access the global variable
print(local_variable) # Access the local variable
}
Output
22
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Inline function:
An inline function in R refers to defining and using a function directly in a single line,
without giving it a formal name or storing it separately.
This is often done using anonymous functions—functions that are created on the fly
and typically used immediately in expressions or as arguments to other functions.
Example:
# Inline function to add two numbers
result <- (function(a, b)
{
return(a + b)
}
)(3, 4)
# Print the result
print(paste("The sum is", result))
Output
Exception:
In R programming, an exception is an error or unexpected event that occurs during
the execution of a program, disrupting the normal flow of the program. R provides
mechanisms to handle these exceptions so that the program can continue running or fail
gracefully.
Handling Exceptions in R
In R, exceptions are generally handled using try(), tryCatch(), or withCallingHandlers()
functions. These functions allow you to manage errors, warnings, and other conditions that may
arise during the execution of code.
1. Using try():
In R programming, the try() function is used to attempt the execution of an expression
that might generate an error, without stopping the execution of the entire script.
If an error occurs, try() catches the error and allows the program to continue
running. This is particularly useful when you want to ensure that your code continues executing
even if a particular operation fails.
General Syntax:
result <- try(expression, silent = FALSE)
23
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Explanation
expression: The code block where an error might occur.
silent: If set to TRUE, suppresses the error message. Default is FALSE.
Example
# Attempt to divide two numbers using try()
result <- try(10 / 0, silent = FALSE)
# Check if the result is an error
if (inherits(result, "try-error"))
{
print("An error occurred during division.")
}
else
{
print(paste("The result of division is:", result))
}
Output
2. Using tryCatch()
In R programming, tryCatch() is a more powerful and flexible tool than try() for
handling exceptions (errors, warnings, or other conditions). It allows you to specify how different
types of conditions should be handled, providing fine-grained control over what happens when
something goes wrong.
General syntax is
tryCatch({
# Code that might throw an exception
}, error = function(e) {
# Code to handle errors
}, warning = function(w) {
# Code to handle warnings
}, finally = {
# Code that should always run, regardless of an error or warning
})
24
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Explanation
{}: The block of code you want to execute, which might generate an error or a warning.
error = function(e): A block of code that runs if an error occurs. The error object e
contains details about the error.
warning = function(w): A block of code that runs if a warning occurs. The warning
object w contains details about the warning.
finally: A block of code that runs regardless of whether an error or warning occurs, useful
for cleanup tasks.
Example
# Define a function that might produce an error or warning
risky_operation <- function(x, y)
{
tryCatch(
{
if (y == 0)
{
warning("Warning: Division by zero")
}
result <- x / y
print(paste("The result is:", result))
}, error = function(e) {
print(paste("Error occurred:", e$message))
}, warning = function(w) {
print(paste("Warning occurred:", w$message))
}, finally = {
print("Execution of the function is complete.")
})
}
# Test with a valid division
risky_operation(10, 2)
25
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Output
Key Points:
tryCatch() allows detailed handling of different types of conditions (error, warning,
etc.).
error = function(e) is used to specify what happens when an error occurs.
warning = function(w) is used to handle warnings similarly.
finally is always executed, ensuring that any necessary final steps (like resource cleanup)
are taken.
3. withCallingHandlers()
Definition: withCallingHandlers() in R allows you to handle conditions (like errors, warnings,
or messages) immediately as they are signaled during code execution. Unlike tryCatch(), which
handles conditions after they occur, withCallingHandlers() lets you intervene right when the
condition is triggered.
Syntax
withCallingHandlers({
# Code that might signal a condition
}, warning = function(w) {
# Code to handle warnings
}, message = function(m) {
# Code to handle messages
}, error = function(e) {
# Code to handle errors
})
26
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Example
withCallingHandlers({
log(10) # Valid operation
log(-10) # This will produce a warning
}, warning = function(w) {
print("A warning occurred!")
}, message = function(m) {
print("A message occurred!")
}, error = function(e) {
print("An error occurred!")
})
Timings
In R programming, timing generally refers to measuring the amount of time taken by a block of
code or a function to execute. This is useful for performance analysis and optimization.
This example measures the time it takes to sum one million random numbers.
2. [Link]():
Returns the cumulative CPU time used by the current R session up to the point when the
function is called.
27
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
This can be useful for more granular tracking of CPU usage over the course of an entire R
session.
Example:
ptm <- [Link]()
result <- sum(runif(1e6))
[Link]() – ptm
Output
This example calculates the time taken by subtracting the start time from the end time.
3. microbenchmark:
Part of the microbenchmark package, which provides more precise timing
measurements.
Useful for comparing the performance of different code snippets or functions.
Example
# First install the microbenchmark package if not installed
#[Link]("microbenchmark")
library(microbenchmark)
microbenchmark(
rnorm(1000),
mean(rnorm(1000)),
times = 100 # Number of repetitions
)
Example
4. [Link]()
This can be used to get the system’s current time before and after code execution, and then
calculate the difference.
28
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Example:
start_time <- [Link]()
# Some time-consuming code here
end_time <- [Link]()
execution_time <- end_time - start_time
print(execution_time)
Output
29
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
},
sum_builtin = sum(1:10000),
iterations = 100 # Number of times to repeat
)
# Print the results
print(results)
Output
Optimizing timing
Optimizing timing in R involves improving the performance of code by reducing its
execution time. By profiling and analyzing the timing of different sections of code, you can
identify bottlenecks and make adjustments to increase efficiency.
Here, explaining the process of optimizing timing with a practical example using the
[Link]() function for timing and then applying some optimizations to improve
performance.
30
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Output
This shows that the function took 0.03 seconds of user time.
Example
# Optimized version using the sum() function
sum_optimized <- function(n)
{
return(sum(1:n))
}
Output
The optimized version is significantly faster because the built-in sum() function is highly efficient
and avoids the overhead of a loop.
31
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Explanation of Syntax
[Link](expr): Measures the time taken to evaluate expr. It returns a named
vector with components:
o user: Time spent by the CPU on the user code.
o system: Time spent on system-level operations.
o elapsed: Total wall clock time from start to end (most relevant for understanding
real-world performance).
Optimization Steps:
1. Identify slow operations: Using [Link](), you can measure the execution time of
code blocks.
2. Replace inefficient code: Loops and non-vectorized operations are common performance
bottlenecks in R.
3. Use vectorized functions: Functions like sum(), mean(), apply(), and others are
optimized for performance.
4. Re-measure: After optimizing, use [Link]() again to see if the performance
improved.
This process of measuring, identifying bottlenecks, and optimizing can be repeated
for other parts of the code to ensure overall efficiency.
Visibility
In R, visibility determines how variables and values are accessed and whether the
results are printed or returned. When discussing visibility in terms of scope, it's important to
understand how global, local, and lexical scoping rules impact how variables are seen and
accessed in different parts of the program.
1. Global Scope
Variables in the global scope are defined in the global environment, meaning they can
be accessed anywhere in the script unless overshadowed by local variables.
When you define a variable at the global level (outside of any function), it’s visible to all
functions unless a local variable with the same name is defined.
Example
# Global variable
x <- 10
# Function accessing global variable
print_global <- function()
{
print(x) # x is taken from the global scope
}
print_global()
32
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Output
[1] 10
Here, the variable x is defined globally and is visible inside the function print_global().
2. Local Scope
Variables in the local scope are defined within a function. They are visible only within
the function and not outside.
If a variable is defined inside a function, it shadows any global variable with the same
name while the function is running.
Example
# Global variable
x <- 10
# Function with a local variable
print_local <- function()
{
x <- 5 # Local variable x
print(x) # x refers to the local variable
}
print_local() # Output: [1] 5
print(x) # Output: [1] 10 (Global variable remains unchanged)
Output
[1] 5
[1] 10
Here, inside the print_local() function, the local variable x is used, but the global x
remains unchanged after the function execution.
3. Lexical Scope
Lexical scoping refers to the way R determines the value of a variable based on the
environment in which the function was defined, not where it is called.
When a function is called, it first looks for variables in its local environment, then in the
parent environment (where the function was created), and continues up the chain until
it reaches the global environment.
33
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Example:
# Function that returns a function
outer_function <- function(a)
{
inner_function <- function(b)
{
a+b # a is taken from the lexical scope of outer_function
}
return(inner_function)
}
# Create a new function with a = 5 in its environment
new_function <- outer_function(5)
# Call the new function
new_function(3) # Output: [1] 8
Output
[1] 8
34
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
Explanation:
Installing a package: [Link]("package_name") installs the package. In
this case, stats is part of base R, so no need to install or load it.
Accessing non-visible function: stats:::[Link] accesses the internal, non-
exported [Link] function.
Matrix data: matrix(rnorm(100), ncol = 2) creates a matrix with random numbers for
testing.
Clustering: kmeans_internal(data, centers = 3) runs k-means clustering using the
non-visible function.
Packages
Packages in R are collections of functions, data sets, and documentation bundled together. They
extend R's base functionality and provide tools for specific tasks or analyses. Using packages
allows you to leverage the work of the R community and streamline your data analysis
processes.
Key Concepts
1. Installation:
o Packages need to be installed before they can be used.
o Installed packages are stored in a library directory and can be loaded into an R
session when needed.
Example
[Link]("package_name") # Install a package from CRAN
2. Loading:
After installation, you need to load a package into your R session to use its functions and
datasets.
Example
library(package_name) # Load an installed package
3. Package Management:
Use [Link]() to list all installed packages.
Use [Link]("package_name") to uninstall a package.
35
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
GitHub: Many developers host their packages on GitHub, which can be installed using
the devtools package.
Example:
library(devtools)
create_package("path/to/package")
Example
# Install and load the 'ggplot2' package
[Link]("ggplot2")
library(ggplot2)
36
Divya S R, Assistant Professor, Department of Computer Science, Gauribidanur.
Unit 2 R Programming
In this example:
[Link]("ggplot2") installs the ggplot2 package.
library(ggplot2) loads the package into the session.
ggplot() is a function from ggplot2 used to create a scatter plot.
37