Data Science Practicum

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

Salary Distribution Chart


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


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

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)

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)

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