Syntax and Control Flow

Practicum ~ Week 4

Arya Fharezi

Arya Fharezi

NIM : 52250008
Data Science Student Institut Teknologi Sains Bandung
Academic Information
Subject
:
Data Science Programming I
Lecturer
:
Bakti Siregar, M.Sc., CDS.
Active Student - Semester 2

2.5 Independent Practice: Conditional Statements and Loops in R

2.5.1 Objectives

  1. Understand and apply conditional statements (if, if-else, if-else if-else).
  2. Use loops (for loop, while loop, break, next) to analyze a dataset.

1 Employee Dataset

# Load libraries
library(DT)
library(dplyr)
library(plotly)

# CREATE EMPLOYEE DATASET
employees <- data.frame(
  ID          = c(1, 2, 3, 4, 5),
  Name        = c("Bagas", "Joan", "Alya", "Dwi", "Nabil"),
  Age         = c(25, 30, 27, 35, 40),
  Salary      = c(5000, 7000, 6500, 10000, 12000),
  Position    = c("Staff", "Supervisor", "Staff", "Manager", "Director"),
  Performance = c("Good", "Very Good", "Average", "Good", "Very Good"),
  stringsAsFactors = FALSE
)

Employee Table

Interpretation:

This dataset covers 5 employees (aged 25–40) with a clear hierarchy, led by Nabil (Director, 12,000) and starting with Bagas (Staff, 5,000). The color-coded Performance column provides rapid identification: green for Very Good, yellow for Good, and red for Average.


Salary Distribution Chart

Interpretation:

The bar chart demonstrates a strong correlation between job hierarchy and compensation levels, where management positions (Director and Manager) dominate with salaries significantly exceeding 10,000. Interestingly, the data suggests that job seniority is a greater determinant of base pay than performance; for example, Joan earns a lower salary than Dwi despite having a higher performance rating. Furthermore, there is a 1,500 salary variance at the Staff level between Alya and Bagas, which is likely influenced by factors such as age or years of service.


2 Conditional Statements

2.5.2 Bonus Calculation Rules
Determine the bonus level based on employee performance:
  • Very Good → 20% of salary
  • Good → 10% of salary
  • Average → 5% of salary
Tasks: Write a program in R to calculate the bonus for each employee and display: "Name: Bagas, Bonus: 500"
for (i in 1:nrow(employees)) {            # Loop through each row, from row 1 to total rows
  name        <- employees$Name[i]        # Extract employee name from the Name column
  salary      <- employees$Salary[i]      # Extract employee salary from the Salary column
  performance <- employees$Performance[i] # Extract performance rating from the Performance column

  if (performance == "Very Good") {       # Check if performance is Very Good
    bonus <- salary * 0.2                 # Assign 20% of salary as bonus
  } else if (performance == "Good") {     # Check if performance is Good
    bonus <- salary * 0.1                 # Assign 10% of salary as bonus
  } else if (performance == "Average") {  # Check if performance is Average
    bonus <- salary * 0.05                # Assign 5% of salary as bonus
  }                                       # End of if-else block

  cat(paste0("Name: ", name, ", Bonus: ", bonus, "\n")) # Print name and calculated bonus
}                                         # End of for loop
## Name: Bagas, Bonus: 500
## Name: Joan, Bonus: 1400
## Name: Alya, Bonus: 325
## Name: Dwi, Bonus: 1000
## Name: Nabil, Bonus: 2400

Bonus Visualization

Interpretation:

The visualization confirms that bonus distribution is strictly dictated by the performance-based logic. Nabil receives the highest bonus of 2,400 (20% of 12,000), while Alya receives the lowest at 325 (5% of 6,500). Even with identical performance rates, such as Bagas and Dwi (both 10%), the final bonus differs (500 vs 1,000) because the calculation is directly proportional to their respective base salaries.


3 Loops (For & While)

2.5.3 Loops Overview
Use loops to analyze the employee dataset using four techniques:
  • for loop — iterate over all employees to filter by salary
  • while loop — iterate until a condition is met
  • break — exit a loop early when a condition triggers
  • next — skip an iteration and continue to the next (like continue in Python)

3.1 For Loop

Task: Display employees with Salary > 6000
Use a for loop to display a list of employees with a salary greater than 6,000.
for (i in 1:nrow(employees)) {              # Loop through each row index from 1 to total number of rows
  if (employees$Salary[i] > 6000) {         # Check if the employee's salary is greater than 6000
    cat(sprintf("Name: %s, Salary: %d\n",   # Print the employee name (%s) and salary (%d)
                employees$Name[i],          # Retrieve employee name from the 'Name' column
                employees$Salary[i]))       # Retrieve employee salary from the 'Salary' column
  }                                         # End of if block
}                                           # End of for loop
## Name: Joan, Salary: 7000
## Name: Alya, Salary: 6500
## Name: Dwi, Salary: 10000
## Name: Nabil, Salary: 12000

Interpretation:

The for loop accurately filters and prints 4 employees with salaries exceeding 6,000 (Joan, Alya, Dwi, and Nabil). Bagas is definitively excluded as his salary (5,000) falls below the required threshold. This demonstrates the precision of conditional control flow within a loop.


3.2 While Loop

Task: Display employees until "Manager" is found
Use a while loop to display employees one by one until a "Manager" is found, then stop.
i <- 1                                               # Start index at 1 (R is 1-based)

while (i <= nrow(employees)) {                       # Keep looping while index is within range
  name     <- employees$Name[i]                      # Get the current employee's name
  position <- employees$Position[i]                  # Get the current employee's position

  if (position == "Manager") {                       # Check if the position is Manager
    cat(sprintf("Name: %s, Position: Manager (Stop here)\n", name)) # Print and signal stop
    break                                            # Exit the while loop immediately
  } else {
    cat(sprintf("Name: %s, Position: %s\n",          # Print name and position for non-managers
                name, position))
  }

  i <- i + 1                                         # Increment index to move to next employee
}
## Name: Bagas, Position: Staff
## Name: Joan, Position: Supervisor
## Name: Alya, Position: Staff
## Name: Dwi, Position: Manager (Stop here)

Interpretation:

The while loop strictly terminates at the fourth iteration once Dwi (Manager) is identified. Due to the break statement, Nabil is definitively excluded. This confirms the program’s efficiency in halting execution exactly when the target criteria are met.


3.3 Break

Task: Stop loop when Salary > 10,000
Use the break command to stop the loop immediately when an employee with a salary above 10,000 is found.
for (i in 1:nrow(employees)) {                       # Loop through each employee row by index
  name   <- employees$Name[i]                        # Get the current employee's name
  salary <- employees$Salary[i]                      # Get the current employee's salary

  if (salary > 10000) {                              # Check if salary exceeds 10,000
    cat(sprintf("(Stopped because %s has a salary above 10,000)\n", name)) # Print stop message
    break                                            # Exit the loop immediately
  }

  cat(sprintf("Name: %s, Salary: %d\n", name, salary)) # Print name and salary if not stopped
}
## Name: Bagas, Salary: 5000
## Name: Joan, Salary: 7000
## Name: Alya, Salary: 6500
## Name: Dwi, Salary: 10000
## (Stopped because Nabil has a salary above 10,000)

Interpretation:

The break command definitively stops the loop at Nabil as his salary (12,000) exceeds the limit. No further data is processed, confirming break as an efficient automated “kill switch” for the program.


3.4 Next (Continue)

Task: Skip employees with "Average" performance
Use the next command (equivalent to continue in Python) to skip any employee with "Average" performance and continue to the next iteration.
for (i in 1:nrow(employees)) {                       # Loop through each employee
  name        <- employees$Name[i]                   # Get employee name
  performance <- employees$Performance[i]            # Get employee performance

  if (performance == "Average") {                    # Skip Average employees
    cat(sprintf("(%s is skipped because the performance is \"Average\")\n", name))
    next                                             # Jump to next iteration
  }

  cat(sprintf("Name: %s, Performance: %s\n", name, performance))
}
## Name: Bagas, Performance: Good
## Name: Joan, Performance: Very Good
## (Alya is skipped because the performance is "Average")
## Name: Dwi, Performance: Good
## Name: Nabil, Performance: Very Good

Interpretation:

The next command accurately skips Alya due to her Average performance. Unlike break, the iteration cycle continues until all other employee data is processed.