Control flow structures allow us to control the execution of code based on conditions and repetitions.
Decision making in programming allows us to control the flow of execution based on specific conditions. In R, various decision-making structures help us execute statements conditionally. These include:
The if statement evaluates a condition and executes code
only if the condition is TRUE.
Syntax:
Example:
a <- 76
b <- 67
if (a > b) {
c <- a - b
print("condition a > b is TRUE")
print(paste("Difference between a, b is:", c))
}#> [1] "condition a > b is TRUE"
#> [1] "Difference between a, b is: 9"
if (a < b) {
c <- a - b
print("condition a < b is TRUE")
print(paste("Difference between a, b is:", c))
}Key Points:
The if-else statement provides an alternative action
when the condition is FALSE.
Syntax:
Example:
a <- 67
b <- 76
if (a > b) {
c <- a - b
print("condition a > b is TRUE")
print(paste("Difference between a, b is:", c))
} else {
c <- a - b
print("condition a > b is FALSE")
print(paste("Difference between a, b is:", c))
}#> [1] "condition a > b is FALSE"
#> [1] "Difference between a, b is: -9"
Practical Example: Grade Classification
score <- 85
if (score >= 90) {
grade <- "A"
} else {
grade <- "B or lower"
}
print(paste("Your grade is:", grade))#> [1] "Your grade is: B or lower"
Multiple conditions are evaluated sequentially until one is TRUE.
Syntax:
if (condition1) {
# execute if condition1 is TRUE
} else if (condition2) {
# execute if condition2 is TRUE
} else {
# execute if all conditions are FALSE
}Example:
a <- 67
b <- 76
c <- 99
if (a > b && b > c) {
print("condition a > b > c is TRUE")
} else if (a < b && b > c) {
print("condition a < b > c is TRUE")
} else if (a < b && b < c) {
print("condition a < b < c is TRUE")
}#> [1] "condition a < b < c is TRUE"
Practical Example: Complete Grade System
score <- 78
if (score >= 90) {
grade <- "A"
message <- "Excellent!"
} else if (score >= 80) {
grade <- "B"
message <- "Very Good!"
} else if (score >= 70) {
grade <- "C"
message <- "Good!"
} else if (score >= 60) {
grade <- "D"
message <- "Pass"
} else {
grade <- "F"
message <- "Fail"
}
cat(sprintf("Score: %d\nGrade: %s\n%s\n", score, grade, message))#> Score: 78
#> Grade: C
#> Good!
An if-else statement inside another if-else statement.
Syntax:
if (parent_condition) {
if (child_condition1) {
# code
} else {
# code
}
} else {
if (child_condition2) {
# code
} else {
# code
}
}Example:
a <- 10
b <- 11
if (a == 10) {
if (b == 10) {
print("a:10 b:10")
} else {
print("a:10 b:11")
}
} else {
if (a == 11) {
print("a:11 b:10")
} else {
print("a:11 b:11")
}
}#> [1] "a:10 b:11"
Practical Example: Login System
username <- "admin"
password <- "pass123"
if (username == "admin") {
if (password == "pass123") {
print("✓ Login successful!")
} else {
print("✗ Incorrect password")
}
} else {
if (username == "") {
print("✗ Username cannot be empty")
} else {
print("✗ User not found")
}
}#> [1] "✓ Login successful!"
Compares an expression against multiple cases and executes matching code.
Syntax:
Example with Numbers:
day_num <- 3
day_name <- switch(day_num,
"1" = "Monday",
"2" = "Tuesday",
"3" = "Wednesday",
"4" = "Thursday",
"5" = "Friday",
"6" = "Saturday",
"7" = "Sunday",
"Invalid day")
print(paste("Day", day_num, "is", day_name))#> [1] "Day 3 is Wednesday"
Example with Characters:
operation <- "add"
result <- switch(operation,
"add" = 5 + 3,
"subtract" = 5 - 3,
"multiply" = 5 * 3,
"divide" = 5 / 3,
"Unknown operation")
print(paste("Result:", result))#> [1] "Result: 8"
Loops allow repetitive execution of code blocks.
Used when the number of iterations is known beforehand.
Syntax:
Example 1: Simple Sequence
#> [1] 1
#> [1] 2
#> [1] 3
#> [1] 4
#> [1] 5
Example 2: Days of the Week
week <- c('Sunday', 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday')
for (day in week) {
print(day)
}#> [1] "Sunday"
#> [1] "Monday"
#> [1] "Tuesday"
#> [1] "Wednesday"
#> [1] "Thursday"
#> [1] "Friday"
#> [1] "Saturday"
Example 3: Loop on a List
my_list <- list(1, 2, 3, 4, 5)
for (i in seq_along(my_list)) {
current_element <- my_list[[i]]
print(paste("Element", i, "is:", current_element))
}#> [1] "Element 1 is: 1"
#> [1] "Element 2 is: 2"
#> [1] "Element 3 is: 3"
#> [1] "Element 4 is: 4"
#> [1] "Element 5 is: 5"
Example 4: Loop on a Matrix
#> [1] "Matrix:"
#> [,1] [,2] [,3]
#> [1,] 1 4 7
#> [2,] 2 5 8
#> [3,] 3 6 9
#>
#> Iterating through matrix:
for (i in seq_len(nrow(my_matrix))) {
for (j in seq_len(ncol(my_matrix))) {
current_element <- my_matrix[i, j]
cat(sprintf("Position [%d,%d] = %d\n", i, j, current_element))
}
}#> Position [1,1] = 1
#> Position [1,2] = 4
#> Position [1,3] = 7
#> Position [2,1] = 2
#> Position [2,2] = 5
#> Position [2,3] = 8
#> Position [3,1] = 3
#> Position [3,2] = 6
#> Position [3,3] = 9
Example 5: Loop on a Data Frame
my_dataframe <- data.frame(
Name = c("Joy", "Juliya", "Boby", "Marry"),
Age = c(40, 25, 19, 55),
Gender = c("M", "F", "M", "F")
)
print("Data Frame:")#> [1] "Data Frame:"
#> Name Age Gender
#> 1 Joy 40 M
#> 2 Juliya 25 F
#> 3 Boby 19 M
#> 4 Marry 55 F
#>
#> Iterating through rows:
for (i in seq_len(nrow(my_dataframe))) {
current_row <- my_dataframe[i, ]
cat(sprintf("Row %d: %s, Age %d, Gender %s\n",
i, current_row$Name, current_row$Age, current_row$Gender))
}#> Row 1: Joy, Age 40, Gender M
#> Row 2: Juliya, Age 25, Gender F
#> Row 3: Boby, Age 19, Gender M
#> Row 4: Marry, Age 55, Gender F
Runs as long as a condition is TRUE. Number of iterations unknown beforehand.
Syntax:
Example 1: Display Numbers 1 to 5
#> [1] 1
#> [1] 2
#> [1] 3
#> [1] 4
#> [1] 5
Example 2: Calculate Factorial
n <- 5
factorial <- 1
i <- 1
while (i <= n) {
factorial <- factorial * i
i <- i + 1
}
print(paste("Factorial of", n, "is", factorial))#> [1] "Factorial of 5 is 120"
Example 3: Input Validation (Simulation)
attempts <- 0
max_attempts <- 3
success <- FALSE
while (attempts < max_attempts && !success) {
attempts <- attempts + 1
# Simulate user input (would normally use readline())
input_value <- sample(c(TRUE, FALSE), 1)
if (input_value) {
success <- TRUE
print(paste("✓ Success on attempt", attempts))
} else {
print(paste("✗ Failed attempt", attempts))
}
}#> [1] "✗ Failed attempt 1"
#> [1] "✗ Failed attempt 2"
#> [1] "✗ Failed attempt 3"
#> [1] "Maximum attempts reached!"
Executes indefinitely until explicitly stopped with
break.
Syntax:
Example 1: Display Numbers 1 to 5
#> [1] 1
#> [1] 2
#> [1] 3
#> [1] 4
#> [1] 5
Example 2: Repeat Statement
#> [1] "Data 4 Data!"
#> [1] "Data 4 Data!"
#> [1] "Data 4 Data!"
#> [1] "Data 4 Data!"
#> [1] "Data 4 Data!"
Example 3: Menu System
counter <- 0
repeat {
counter <- counter + 1
# Simulate menu selection
choice <- sample(1:4, 1)
cat(sprintf("\nIteration %d - Choice: %d\n", counter, choice))
if (choice == 1) {
print("Option 1 selected")
} else if (choice == 2) {
print("Option 2 selected")
} else if (choice == 3) {
print("Option 3 selected - Exiting")
break
} else {
print("Invalid option")
}
# Safety break after 10 iterations
if (counter >= 10) {
print("Max iterations reached")
break
}
}#>
#> Iteration 1 - Choice: 2
#> [1] "Option 2 selected"
#>
#> Iteration 2 - Choice: 3
#> [1] "Option 3 selected - Exiting"
Exits the loop immediately.
#> [1] 1
#> [1] 2
#> [1] 3
#> [1] 4
#> [1] 5
#> [1] "Breaking at 6"
A Version Control System (VCS) is a tool that tracks and manages changes to source code over time. It enables:
Examples: SVN (Subversion), CVS
Architecture: - Single central server stores all files - Developers check out files from central location - Changes committed directly to central server
Workflow: 1. Checkout/Update: Get latest files from server 2. Make Changes: Edit files locally 3. Commit: Save changes to central server
Pros: - Easy to understand and manage - Fine-grained access control - Everyone sees what others are doing
Cons: - Single point of failure (server down = no work) - Requires network connection - Limited offline capabilities
Examples: Git, Mercurial, Bazaar
Architecture: - Every developer has full repository copy - Complete history available locally - Changes shared through push/pull
Workflow: 1. Commit: Save changes to local repository 2. Push: Upload changes to remote repository 3. Pull/Fetch: Download changes from remote repository
Pros: - Fast operations (local) - Work offline - Multiple backup copies - Flexible workflows - No single point of failure
Cons: - Steeper learning curve - More complex commands
Git is an open-source distributed version control system designed for:
Created by: Linus Torvalds (2005)
Purpose: Managing Linux kernel development
License: GPL v2 (Free and Open Source)
Working Directory → (git add) → Staging Area → (git commit) → Repository
Windows: Download Git for Windows (includes Git
Bash)
Mac: brew install git or download from
git-scm.com
Linux: sudo apt-get install git
(Ubuntu/Debian)
# Set username
git config --global user.name "Your Name"
# Set email
git config --global user.email "your.email@example.com"
# Check configuration
git config --list
# Set default editor
git config --global core.editor "vim"
# Set default branch name
git config --global init.defaultBranch main# Create new branch
git branch feature-branch
# Switch to branch
git checkout feature-branch
# Create and switch (shortcut)
git checkout -b feature-branch
# Modern way (Git 2.23+)
git switch feature-branch
git switch -c new-branch
# List branches
git branch
git branch -a # include remote branches
# Delete branch
git branch -d feature-branch
git branch -D feature-branch # force delete
# Delete remote branch
git push origin --delete feature-branch# Discard changes in working directory
git restore filename.R
git checkout -- filename.R # old way
# Unstage file
git restore --staged filename.R
git reset HEAD filename.R # old way
# Revert a commit
git revert <commit-hash>
# Reset to previous commit
git reset --soft HEAD~1 # keep changes
git reset --mixed HEAD~1 # unstage changes
git reset --hard HEAD~1 # discard changes (⚠️ dangerous!)Good commit message format:
Short summary (50 chars or less)
Detailed explanation if needed. Wrap at 72 characters.
Explain what and why, not how.
- Bullet points are okay
- Use present tense: "Add feature" not "Added feature"
Examples:
Common strategies:
main: Production codedevelop: Integration branchfeature/*: New featureshotfix/*: Emergency fixesmain: Always deployablefeature/*: All developmentmain: Single integration branch# R specific
.Rproj.user
.Rhistory
.RData
.Ruserdata
*.Rproj
# Data files (if large)
*.csv
*.xlsx
data/
# Output files
*.pdf
*.png
figures/
# OS specific
.DS_Store
Thumbs.db
RStudio has built-in Git integration:
GitHub is a web-based platform for hosting Git repositories and collaborating on code.
| Feature | Git | GitHub |
|---|---|---|
| Type | Version control tool | Hosting service |
| Location | Local computer | Cloud-based |
| Purpose | Track changes | Collaboration platform |
| Access | Command line/GUI | Web interface + Git |
| Created by | Linus Torvalds | Chris Wanstrath, et al. |
| Owned by | Linux community | Microsoft |
On GitHub: 1. Click “New repository” 2. Enter repository name 3. Add description (optional) 4. Choose public/private 5. Initialize with README (optional) 6. Add .gitignore template 7. Choose license 8. Click “Create repository”
From Command Line:
Fork = Personal copy of someone else’s repository
Creating a Pull Request:
Reviewing Pull Requests: - Review code changes - Add comments - Approve or request changes - Merge when approved
git checkout -b feature/AmazingFeature)git commit -m 'Add some AmazingFeature')git push origin feature/AmazingFeature)# .github/workflows/r-check.yml
name: R-CMD-check
on: [push, pull_request]
jobs:
R-CMD-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: r-lib/actions/setup-r@v2
- name: Install dependencies
run: |
install.packages(c("remotes", "rcmdcheck"))
shell: Rscript {0}
- name: Check
run: rcmdcheck::rcmdcheck(args = "--no-manual", error_on = "error")
shell: Rscript {0}Create a grade calculator that: - Takes a score input - Uses if-else-if to assign letter grade - Uses switch to assign GPA - Prints formatted result
Write R code to: - Calculate Fibonacci sequence (for loop) - Find prime numbers (while loop) - Create menu system (repeat loop)
End of Notes
Created with R Markdown 📝