Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 26

R

PROGRAMMIN
G
Agenda

• Overview of R Programming
• Variables and Data Types
• Data Structures
• Control Statements: if, else, else if, switch
• Loops: for, while, repeat, break, next
• Functions and Strings
Introduction

• R is a programming language and open-source software


environment specifically designed for statistical computing
and data analysis.
• Developed by statisticians Ross Ihaka and Robert
Gentleman at the University of Auckland, New Zealand.
• Widely used in academia, research, and industry for
statistical analysis, machine learning, and data
visualization.
VARIABLES AND DATA
TYPES
What is a Variable?
• A variable is a symbolic name assigned to a
value or data.
• Used to store and manipulate information in a
program.
Assigning values to variables:
- Use the ‘<‘ or ‘=‘ operator.
Age <- 25
Basic Data Types
•Numeric Data Type:
•Represents numbers, both
integers and decimals.
•Example: x <- 5 or y <- 3.14
•Character Data Type:
•Represents text or strings.
•Example: name <- "John"
•Logical Data Type:
•Represents binary values: TRUE
or FALSE.
•Example: is_valid <- TRUE
DATA
STRUCTURES
Introduction

• Essential for organizing and storing data in R.


• Different types cater to various needs in data
manipulation and analysis.
What is a Vector?
• A one-dimensional array that can hold numeric, character,
or logical values.
numeric_vector <- c(1, 2, 3, 4, 5)
first_element <- numeric_vector[1]
What is a Matrix?
• A two-dimensional array with rows and columns.
matrix_example <- matrix(1:6, nrow = 2, ncol = 3)
element_2_3 <- matrix_example[2, 3]
What is a List?
• A collection of ordered elements, which can be of different
types.
my_list <- list("apple", 2, TRUE)
second_element <- my_list[[2]]
What is a Data Frame?
• A two-dimensional structure similar to a matrix but with
more flexibility.

df <- data.frame(
Name = c("Alice", "Bob",
"Charlie"),
Age = c(25, 30, 22),
Grade = c("A", "B", "C")
)
ages <- df$Age
CONTROL STATEMENTS
Introduction
• Essential for controlling the flow of execution in a program.
• Make decisions based on conditions.
Use cases
• Decision Making:
– Control statements are crucial for decision-making in
programs.
• Handling Multiple Conditions:
– Else-If is useful when you have multiple conditions to check.
• Switch for Categorical Data:
– Switch is handy when dealing with categorical variables.
‘If’ Statement
• The ‘if’ statement is a fundamental control structure in R.
• It allows you to execute a block of code only if a specified condition is
true.
Syntax:
if (condition) {
# code block to execute if condition is TRUE
}
Example:
x <- 7
if (x > 0) {
print("The number is positive.")
}
If – Else Statement
• The ‘if-else’ statement is used to execute one block of code if
the condition is true and another block if the condition is false.
Example:
y <- 3
if (y %% 2 == 0) {
print("y is even")
} else {
print("y is odd")
}
Else-If Statement
• The ‘else-if’ statement is used to check multiple conditions
sequentially.
Example:
grade <- 75
if (grade >= 90) {
print("A")
} else if (grade >= 80) {
print("B")
} else if (grade >= 70) {
print("C")
} else {
print("F")
}
LOOPS
‘For’ Loops

• The ‘for’ loop is used to iterate over a sequence (e.g., a


vector, list, or sequence of numbers).

for (i in 1:5) {
print(paste("Iteration:", i))
}
‘While’ Loop

• The loop is used to execute a block of code as long as a


condition is true.

count <- 1

while (count <= 5) {


print(paste("Iteration:", count))
count <- count + 1
}
‘Repeat’ Loop
• The loop is used to execute a block of code indefinitely until a ‘break’ statement is
encountered.

count <- 1

repeat {
print(paste("Iteration:", count))
count <- count + 1

if (count > 5) {
break
}
}
‘Break’ and ‘Next’ Statement
• The ‘break’ statement is used to exit a loop prematurely.
• The ‘next’ statement is used to skip the rest of the current iteration and move to the next
one.
for (i in 1:10) {
if (i %% 2 == 0) {
next # Skip even numbers
}

print(paste("Iteration:", i))

if (i == 7) {
break # Exit the loop when i equals 7
}
}
FUNCTIONS AND STRINGS
Functions

• A function is a block of reusable code designed to perform a specific task.


• Functions in R are essential for modularizing code, improving code readability, and
promoting code reuse.

Example:
add_numbers <- function(x, y) {
result <- x + y
return(result)
}

# Using the function


sum_result <- add_numbers(3, 5)
print(sum_result)
User- Defined Function
• You can create your own functions tailored to specific tasks. These functions can have
parameters and can return values.
Example:
is_even <- function(num) {
if (num %% 2 == 0) {
return(TRUE)
} else {
return(FALSE)
}
}

# Using the function


result <- is_even(6)
print(result) # Output: TRUE
Apply Function

• The ‘apply’ family of functions (e.g., ‘lapply’, ‘sapply’,


‘mapply’ , etc.) are used for applying a function to the
elements of lists, vectors, or matrices.
Example:
numbers_list <- list(a = 2, b = 3, c = 4)
squared_list <- lapply(numbers_list, function(x) x^2)

print(squared_list)
Strings
• Strings in R are represented as character vectors. Here are some
common operations with strings.

Concatenating Strings:
• concatenate strings using the ‘paste()’ function.
first_name <- "John"
last_name <- "Doe"
full_name <- paste(first_name, last_name, sep = " ")

print(full_name)
Substring and Case Conversion:
• R provides functions for extracting substrings and
converting case.
text <- "Hello, World!"
substring_result <- substr(text, start = 1, stop = 5)
uppercase_result <- toupper(text)

print(substring_result)
print(uppercase_result)
• ‘substr(text,start = 1, stop = 5)’ extracts a substring
from the 1st to the 5th character.

You might also like