Unit-5 (R-Programming)
Unit-5 (R-Programming)
1. What is R?
● Statistical Computing and Graphics: R's primary strength lies in its comprehensive
suite of tools for statistical analysis, modeling, and creating high-quality data
visualizations.
● Open-Source and Free: R is freely available for anyone to use, modify, and
distribute. This fosters a vibrant community and a wealth of shared resources.
● Interpreted Language: Unlike compiled languages, R executes code line by line
through a command-line interpreter, allowing for interactive data exploration and
immediate feedback.
● Domain-Specific Language (DSL): While not a general-purpose language like
Python or Java, R is highly specialized for data-related tasks, making it incredibly
efficient for its intended domain.
● High-Level Language: R is designed to be easily understood and written by humans,
abstracting away complex computer memory and processes.
● Data Analysis and Statistics: R is the go-to language for statisticians and data
analysts for performing in-depth statistical analysis, hypothesis testing, and exploring
data patterns.
● Data Visualization: Creating compelling and insightful graphs, charts, and
dashboards is a core application of R.
● Machine Learning and Data Science: R is widely used for building predictive
models, implementing machine learning algorithms, and conducting data science
projects.
● Financial Analysis: In finance, R is used for quantitative modeling, risk analysis, and
portfolio management.
● Healthcare and Bioinformatics: R plays a crucial role in analyzing medical data,
conducting clinical research, and performing genomic analysis.
● Academic Research: Researchers across disciplines rely on R for data analysis and
publishing reproducible results.
● Install R: Download and install the R base system from the official CRAN website.
● Choose an IDE (Integrated Development Environment): While R comes with a
command-line interface, using an IDE like RStudio is highly recommended. RStudio
provides a user-friendly environment with features like syntax highlighting, code
completion, and integrated help.
● Learn Basic Syntax: Familiarize yourself with R's fundamental concepts, including
data types (vectors, lists, data frames), operators, control flow (loops, conditionals),
and functions.
● Explore Packages: Start using popular packages like dplyr for data manipulation and
ggplot2 for data visualization to leverage R's true power.
In essence, R is an indispensable tool for anyone working with data, offering a powerful and
flexible environment for statistical computing, analysis, and visualization. Its open-source
nature, extensive community, and rich ecosystem of packages make it a continuous evolving
and highly valuable asset in the world of data science.
Operators:
In R programming, operators are special symbols or keywords that perform specific
operations on values and variables. Understanding them is fundamental to writing any R
code, as they allow you to manipulate data, perform calculations, make comparisons, and
control program flow.
1. Arithmetic Operators
Example:
R
x <- 10
y <- 3
print(x + y) # Output: 13
print(x - y) # Output: 7
print(x * y) # Output: 30
print(x / y) # Output: 3.333333
print(x %% y) # Output: 1 (remainder of 10 / 3)
print(x %/% y) # Output: 3 (integer part of 10 / 3)
print(2^4) # Output: 16
These operators are used to compare two values and return a logical (TRUE or FALSE)
result.
Example:
R
a <- 7
b <- 5
3. Logical Operators
These operators combine or negate logical values (TRUE or FALSE). They are often used
with relational operators to create more complex conditions.
Operat Resul
Description Example
or t
FALS
& Element-wise Logical AND TRUE & FALSE
E
Logical AND (evaluates only the FALS
&& TRUE && FALSE
first element) E
`TRU
` ` Element-wise Logical OR
E
Logical OR (evaluates only the `TRU
` `
first element) E
FALS
! Logical NOT !TRUE
E
Export to Sheets
● & (element-wise AND) and | (element-wise OR): These operators perform element-
wise comparisons when applied to vectors. They return a logical vector of the same
length as the input.
● && (logical AND) and || (logical OR): These operators are typically used in control
flow statements (like if statements). They only evaluate the first element of each
vector and return a single TRUE or FALSE value. This is a "short-circuiting"
evaluation.
Example:
R
x <- c(TRUE, FALSE, TRUE)
y <- c(TRUE, TRUE, FALSE)
if (x[2] || y[2]) {
print("At least one of the first elements is TRUE") # Output: "At least one of the first
elements is TRUE"
}
4. Assignment Operators
Operat
Description Example
or
<- Leftward Assignment (preferred) my_var <- 10
= Assignment (also works, but often used for function arguments) my_var = 10
-> Rightward Assignment 10 -> my_var
Global Assignment (for modifying variables in parent global_var
<<-
environments within functions) <<- 20
20 ->>
->> Global Rightward Assignment
global_var
Export to Sheets
Example:
R
# Preferred assignment
my_number <- 15
print(my_number) # Output: 15
# Rightward assignment
30 -> third_number
print(third_number) # Output: 30
# Global assignment (primarily used within functions to affect variables outside their local
scope)
# Example:
# my_function <- function() {
# global_variable <<- 100
#}
# my_function()
# print(global_variable) # Output: 100
5. Miscellaneous Operators
Operat
Description Example Result
or
: Sequence Operator 1:5 [1] 1 2 3 4 5
Membership Operator (checks if an
%in% 3 %in% c(1, 2, 3, 4) TRUE
element is present in a vector)
(Resulting
%*% Matrix Multiplication matrix1 %*% matrix2
matrix)
Component Extraction (for lists, my_dataframe$column_na (Column
$
data frames) me data)
Indexing (for vectors, lists, data (Second
[] my_vector[2]
frames, matrices) element)
Export to Sheets
Example:
R
# Sequence operator
numbers <- 1:5
print(numbers) # Output: [1] 1 2 3 4 5
# Membership operator
fruits <- c("apple", "banana", "cherry")
print("banana" %in% fruits) # Output: TRUE
print("grape" %in% fruits) # Output: FALSE
# Indexing a vector
my_vec <- c(10, 20, 30, 40)
print(my_vec[3]) # Output: [1] 30
Operator Precedence:
Just like in mathematics, operators in R have an order of precedence. Operations with higher
precedence are performed before operations with lower precedence. For example,
multiplication and division are performed before addition and subtraction. Parentheses () can
be used to override the default precedence.
Understanding and effectively utilizing these operators is crucial for writing efficient and
readable R code for data analysis and statistical computing.
Control Statements:
In R programming, control statements are fundamental constructs that allow you to dictate
the flow of execution in your code. They enable you to make decisions, repeat actions, and
handle different scenarios based on specific conditions. This makes your programs dynamic
and capable of responding to varying inputs and data.
These statements execute a block of code only if a specified condition evaluates to TRUE.
a) if Statement
Syntax:
R
if (condition) {
# code to be executed if condition is TRUE
}
Example:
R
x <- 10
if (x > 5) {
print("x is greater than 5")
}
b) if-else Statement
Executes one block of code if the condition is TRUE and another block if it's FALSE.
Syntax:
R
if (condition) {
# code to be executed if condition is TRUE
} else {
# code to be executed if condition is FALSE
}
Example:
R
temperature <- 28
Syntax:
R
if (condition1) {
# code if condition1 is TRUE
} else if (condition2) {
# code if condition2 is TRUE
} else {
# code if no condition is TRUE
}
Example:
R
score <- 85
d) ifelse() Function
A vectorized version of if-else, useful for applying a condition to each element of a vector. It
returns a vector of results.
Syntax:
R
ifelse(test, yes, no)
Where:
Example:
R
ages <- c(15, 22, 18, 30, 16)
can_vote <- ifelse(ages >= 18, "Yes", "No")
print(can_vote)
# Output: [1] "No" "Yes" "Yes" "Yes" "No"
e) switch() Statement
Useful for selecting one of many code blocks to execute based on the value of an expression.
It's often cleaner than long if-else if chains for specific value comparisons.
Syntax:
R
switch(expression,
case1 = result1,
case2 = result2,
...,
default_case = default_result # optional
)
R
day_of_week <- "Tuesday"
R
choice <- 2
a) for Loop
Executes a block of code for each element in a sequence (vector, list, data frame columns,
etc.).
Syntax:
R
for (variable in sequence) {
# code to be executed for each element
}
R
for (i in 1:5) {
print(paste("Number:", i))
}
b) while Loop
Repeats a block of code as long as a specified condition is TRUE. It's crucial to ensure that
the condition eventually becomes FALSE to avoid an infinite loop.
Syntax:
R
while (condition) {
# code to be executed as long as condition is TRUE
}
Example:
R
count <- 1
c) repeat Loop
Repeats a block of code indefinitely until an explicit break statement is encountered within
the loop.
Syntax:
R
repeat {
# code to be executed repeatedly
if (condition_to_break) {
break # exits the loop
}
}
Example:
R
i <- 1
repeat {
print(paste("Repeating...", i))
i <- i + 1
if (i > 3) {
break # Exit the loop when i is greater than 3
}
}
# Output:
# [1] "Repeating... 1"
# [1] "Repeating... 2"
# [1] "Repeating... 3"
These statements allow you to alter the normal execution flow of loops.
a) break Statement
Terminates the loop immediately and transfers control to the statement immediately
following the loop.
Example:
R
for (i in 1:10) {
if (i == 5) {
print("Breaking loop at 5")
break # Exits the loop
}
print(i)
}
# Output:
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] "Breaking loop at 5"
b) next Statement
Skips the rest of the current iteration of the loop and proceeds to the next iteration.
Example:
R
for (i in 1:5) {
if (i == 3) {
print("Skipping number 3")
next # Skips the rest of this iteration
}
print(paste("Current number:", i))
}
# Output:
# [1] "Current number: 1"
# [1] "Current number: 2"
# [1] "Skipping number 3"
# [1] "Current number: 4"
# [1] "Current number: 5"
Functions:
● Reusability: Write a block of code once and use it multiple times throughout your
program or even in different projects.
● Modularity: Break down complex problems into smaller, manageable units, making
your code easier to understand, debug, and maintain.
● Abstraction: Hide complex implementation details, allowing users to focus on what
the function does rather than how it does it.
● Readability: Well-named functions improve the clarity and readability of your code.
● Reduced Errors: By centralizing logic in a function, you minimize the risk of
inconsistencies and errors that can arise from copying and pasting code.
R supports both built-in functions (pre-defined functions that come with R or its packages)
and user-defined functions (functions you create yourself).
1. Built-in Functions
R comes with a vast library of built-in functions for almost any data-related task. You've
likely already encountered some of them.
Example usage:
R
numbers <- c(10, 20, 30, 40, 50)
print(mean(numbers)) # Output: 30
print(sum(numbers)) # Output: 150
print(max(numbers)) # Output: 50
2. User-Defined Functions
You can create your own functions in R to encapsulate specific logic tailored to your needs.
R
function_name <- function(argument1, argument2, ...) {
# Function body: R code to perform the task
# Last evaluated expression is typically the return value (explicit 'return()' is optional)
return(result) # Optional: explicitly return a value
}
Components of a Function:
● function_name: The name you give to your function. It should be descriptive and
follow R's naming conventions (e.g., my_function, calculate_average).
● <- (assignment operator): Used to assign the function definition to function_name.
● function() keyword: This keyword indicates that you are defining a function.
● arguments (parameters): A comma-separated list of inputs that the function accepts,
enclosed in parentheses (). These are placeholders for values that will be passed when
the function is called. Arguments can have default values.
● {} (curly braces): The function body, containing the R statements that will be
executed when the function is called.
● return() (optional): Specifies the value(s) the function should send back to the caller.
If return() is not used, the function automatically returns the value of the last
evaluated expression in the function body.
R
# Define the function
add_numbers <- function(a, b) {
sum_result <- a + b
return(sum_result) # Explicitly return the sum
}
R
multiply_numbers <- function(x, y) {
x * y # This expression's value will be returned
}
You can assign default values to arguments. If the user doesn't provide a value for that
argument when calling the function, the default value is used.
R
# Define a function to calculate power with a default exponent
calculate_power <- function(base, exponent = 2) {
result <- base ^ exponent
return(result)
}
R
# Define a function to calculate descriptive statistics
get_summary_stats <- function(data_vector) {
if () {
stop("Input must be a numeric vector.") # Error handling
}
3. Mixing Position and Name: You can mix both, but positional arguments must come
before named arguments.
R uses "lazy evaluation" for function arguments. This means that arguments are only
evaluated when they are actually used within the function body. If an argument is not used, it
is never evaluated.
R
lazy_example <- function(a, b) {
print(paste("Value of a:", a))
# 'b' is never used, so it's not evaluated
}
Functions are central to programming effectively in R, enabling you to write clean, modular,
and maintainable code for all your data analysis and statistical tasks.
1. Vectors
Vectors are the most basic data structure in R. They are one-dimensional arrays that can hold
a sequence of elements of the same data type. If you try to mix data types, R will coerce all
elements to the most flexible type (e.g., numbers to characters).
Key Characteristics:
● Homogeneous: All elements must be of the same type (numeric, integer, character,
logical, complex).
● One-dimensional: A sequence of elements.
● Created with c(): The c() function (combine or concatenate) is used to create vectors.
Examples:
R
# Numeric Vector
numeric_vec <- c(10, 20, 30, 40, 50)
print(numeric_vec)
print(class(numeric_vec)) # Output: [1] "numeric"
# Character Vector
char_vec <- c("apple", "banana", "cherry")
print(char_vec)
print(class(char_vec)) # Output: [1] "character"
# Logical Vector
logical_vec <- c(TRUE, FALSE, TRUE)
print(logical_vec)
print(class(logical_vec)) # Output: [1] "logical"
# Accessing elements
print(numeric_vec[1]) # First element (R uses 1-based indexing)
print(numeric_vec[c(2, 4)]) # Second and fourth elements
print(numeric_vec[-3]) # All elements except the third
2. Matrices
Matrices are two-dimensional, homogeneous data structures. They are essentially collections
of elements of the same data type arranged in rows and columns.
Key Characteristics:
Examples:
R
# Create a 2x3 matrix
my_matrix <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3)
print(my_matrix)
# Output:
# [,1] [,2] [,3]
# [1,] 1 3 5
# [2,] 2 4 6
print(class(my_matrix)) # Output: [1] "matrix" "array"
# Accessing elements
print(my_matrix[1, 2]) # Element at row 1, column 2
print(my_matrix[2, ]) # All elements of row 2
print(my_matrix[, 3]) # All elements of column 3
print(my_matrix[c(1,2), c(2,3)]) # Subset of rows 1 and 2, columns 2 and 3
3. Lists
Lists are the most flexible data structure in R. They are one-dimensional, but they can hold
collections of objects of different data types and sizes. A list can even contain other lists,
vectors, matrices, data frames, or even functions.
Key Characteristics:
Examples:
R
# Create a list
my_list <- list("Alice", 25, TRUE, c(1, 2, 3), matrix(1:4, nrow=2))
print(my_list)
# Output:
# [[1]]
# [1] "Alice"
#
# [[2]]
# [1] 25
#
# [[3]]
# [1] TRUE
#
# [[4]]
# [1] 1 2 3
#
# [[5]]
# [,1] [,2]
# [1,] 1 3
# [2,] 2 4
print(class(my_list)) # Output: [1] "list"
# Accessing elements
print(my_list[[1]]) # Access first element by position (returns the element itself)
print(my_list[1]) # Access first element by position (returns a list containing that
element)
print(person_info$name) # Access by name using $ operator
print(person_info[["age"]]) # Access by name using double brackets
print(person_info[c("name", "grades")]) # Access multiple named elements (returns a sub-
list)
4. Data Frames
Data frames are the most commonly used data structure for storing tabular data in R. They
are essentially lists of vectors of equal length. Each vector represents a column, and each
element within the vector represents a row. Data frames are similar to tables in a relational
database or spreadsheets in Excel.
Key Characteristics:
Examples:
R
# Create a data frame
students_df <- [Link](
Name = c("Alice", "Bob", "Charlie"),
Age = c(20, 22, 21),
Major = c("Math", "Physics", "Chemistry"),
GPA = c(3.8, 3.5, 3.9)
)
print(students_df)
# Output:
# Name Age Major GPA
# 1 Alice 20 Math 3.8
# 2 Bob 22 Physics 3.5
# 3 Charlie 21 Chemistry 3.9
print(class(students_df)) # Output: [1] "[Link]"
# Accessing elements
print(students_df$Name) # Access column by name using $
print(students_df[["Age"]]) # Access column by name using double brackets
print(students_df[, "Major"]) # Access column by name using square brackets
print(students_df[1, ]) # Access first row
print(students_df[c(1, 3), ]) # Access first and third rows
print(students_df[2, 3]) # Access element at row 2, column 3 (Major for Bob)
5. Factors
Factors are used to store categorical data in R. They are special vectors that represent levels
(categories) rather than raw values. This is particularly useful for statistical modeling, where
categorical variables need to be treated differently from continuous ones.
Key Characteristics:
● Categorical data: Ideal for variables like gender, education level, city, etc.
● Levels: Factors have predefined levels, which are the unique categories the data can
take.
● Ordered or Unordered: Factors can be ordered (e.g., "low" < "medium" < "high") or
unordered.
● Underlying integer representation: R stores factors as integers with labels mapped
to these integers.
Examples:
R
# Create a character vector
gender_char <- c("Male", "Female", "Female", "Male", "Male")
print(gender_char)
# Convert to a factor
gender_factor <- factor(gender_char)
print(gender_factor)
# Output:
# [1] Male Female Female Male Male
# Levels: Female Male (Levels are sorted alphabetically by default)
print(class(gender_factor)) # Output: [1] "factor"
# Check levels
print(levels(gender_factor)) # Output: [1] "Female" "Male"
In R, when people refer to "tables" in the context of data structures, they often mean the
output of functions like table() or ftable(), which generate frequency tables (contingency
tables) to summarize categorical data. These are not a distinct core data type like vectors or
data frames, but rather a specialized array type that is very commonly used for summarizing
data.
Key Characteristics:
● Summarize counts: Show the frequency of occurrences for each unique value (level)
in one or more categorical variables.
● Used for categorical data: Works best with factors or character vectors.
● Multi-dimensional (for multiple variables): Can show cross-tabulations.
Examples:
R
# Frequency table for a single vector (factor)
gender_data <- factor(c("Male", "Female", "Male", "Female", "Female", "Male"))
gender_counts <- table(gender_data)
print(gender_counts)
# Output:
# gender_data
# Female Male
# 3 3
print(class(gender_counts)) # Output: [1] "table"
Data
Dimensio Homogeneous/ Primary Creation
Structu Analogy
ns Heterogeneous Use Case Function
re
Basic A single
Vector 1D Homogeneous sequence c() column in
of values Excel
Rectangul
A grid of
Matrix 2D Homogeneous ar data of matrix()
numbers
same type
Collection A mixed-
List 1D Heterogeneous of diverselist() content
objects folder
Tabular An Excel
Data [Link]
2D Heterogeneous (columns) data (most spreadshe
Frame ()
common) et
Drop-
Categoric
down list
Factor 1D Homogeneous (categorical) al factor()
with
variables
options
Frequency A pivot
Table N-D Homogeneous (counts) table()
counts table
saveRDS(my_df_to_save, "single_df.rds")
# To load later:
# loaded_df <- readRDS("single_df.rds")
# print(loaded_df)
● Saving Plots: R's plotting functions often integrate with device functions like pdf(),
png(), jpeg(), etc., to save plots to files.
# Save as PDF
pdf("my_plot.pdf")
hist(rnorm(100), main = "Histogram of Normal Data")
[Link]()