Professional Documents
Culture Documents
Second
Second
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
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
for (i in 1:5) {
print(paste("Iteration:", i))
}
‘While’ Loop
count <- 1
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
Example:
add_numbers <- function(x, y) {
result <- x + y
return(result)
}
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.