Syntax and Control Flow
Assignment ~ Week 4
1 Introduction
Programming requires clear syntax and logical structures to control how instructions are executed. Two important components in this process are conditional statements and loops, which allow programs to make decisions based on specific conditions and execute code repeatedly to process data efficiently. In the context of data science, these concepts are commonly used to manipulate datasets, automate calculations, and filter relevant information. This report demonstrates the application of syntax and control flow in R using a simple employee dataset to calculate bonuses based on performance and process data using different types of loops and loop control.
2 Dataset
The dataset used in this exercise represents employee information including salary, performance level, and job position. This dataset will serve as the input for demonstrating conditional statements and loop operations in R.
# Membuat dataset karyawan dalam bentuk data frame
employees <- data.frame(
ID = c(1,2,3,4,5), # ID unik setiap karyawan
Name = c("Bagas","Joan","Alya","Dwi","Nabil"), # Nama karyawan
Salary = c(5000,7000,6500,10000,12000), # Gaji masing-masing karyawan
Performance = c("Good","Very Good","Average","Good","Very Good"), # Penilaian performa karyawan
Position = c("Staff","Supervisor","Staff","Manager","Director") # Posisi/jabatan karyawan
)
# Menampilkan dataset yang telah dibuat
employeesThe dataset contains five employee records with information about salary, performance level, and job position. This dataset will be used to demonstrate how programming logic can be applied to perform calculations, filtering, and conditional operations.
3 Conditional Statement
Conditional statements allow a program to execute different actions depending on whether certain conditions are satisfied. In this section, conditional logic is used to calculate employee bonuses based on their performance level.
The bonus policy is defined as follows:
\[ \begin{aligned} \text{Very Good} &\rightarrow 20\% \text{ of salary} \\ \text{Good} &\rightarrow 10\% \text{ of salary} \\ \text{Average} &\rightarrow 5\% \text{ of salary} \end{aligned} \]
# Membuat kolom Bonus dan mengisi nilai awal 0
employees$Bonus <- 0
# Melakukan perulangan untuk setiap baris pada dataset
for (i in 1:nrow(employees)) {
# Jika performa karyawan "Very Good" maka bonus 20% dari gaji
if (employees$Performance[i] == "Very Good") {
employees$Bonus[i] <- employees$Salary[i] * 0.20
}
# Jika performa "Good" maka bonus 10% dari gaji
else if (employees$Performance[i] == "Good") {
employees$Bonus[i] <- employees$Salary[i] * 0.10
}
# Jika performa selain dua kondisi di atas (Average) maka bonus 5%
else {
employees$Bonus[i] <- employees$Salary[i] * 0.05
}
# Menampilkan nama karyawan dan bonus yang diperoleh
cat(paste0("Name: ", employees$Name[i],
", Bonus: ", employees$Bonus[i], "\n"))
}## Name: Bagas, Bonus: 500
## Name: Joan, Bonus: 1400
## Name: Alya, Bonus: 325
## Name: Dwi, Bonus: 1000
## Name: Nabil, Bonus: 2400
# Menghitung total gaji setelah ditambahkan bonus
employees$Total_Salary <- employees$Salary + employees$Bonus
# Menampilkan beberapa kolom penting saja
employees[,c("Name","Salary","Bonus","Total_Salary")]4 Loop
Loops allow a block of code to be executed repeatedly when processing datasets. They are useful when the same operation must be applied to multiple data records.
4.1 For Loop
A for loop is used when the number of iterations is known. In this example, the loop iterates through the dataset and prints employees whose salary is greater than 6000.
# Perulangan untuk mengecek setiap karyawan dalam dataset
for (i in 1:nrow(employees)) {
# Mengecek apakah gaji karyawan lebih dari 6000
if (employees$Salary[i] > 6000) {
# Jika kondisi terpenuhi maka tampilkan nama dan gaji
cat(paste0("Name: ", employees$Name[i],
", Salary: ", employees$Salary[i], "\n"))
}
}## Name: Joan, Salary: 7000
## Name: Alya, Salary: 6500
## Name: Dwi, Salary: 10000
## Name: Nabil, Salary: 12000
4.2 While Loop
A while loop runs repeatedly as long as a specified condition remains true. In this case, the loop continues until an employee with the position Manager is found.
# Inisialisasi indeks awal
i <- 1
# Variabel penanda apakah manager sudah ditemukan
manager_found <- FALSE
# Perulangan berjalan selama indeks masih dalam jumlah data
# dan manager belum ditemukan
while (i <= nrow(employees) && manager_found == FALSE) {
# Mengecek apakah posisi karyawan adalah Manager
if (employees$Position[i] == "Manager") {
# Jika ditemukan manager maka tampilkan informasi
cat("Name:", employees$Name[i],
", Position:", employees$Position[i],
"(Stop here)\n")
# Mengubah status menjadi TRUE agar loop berhenti
manager_found <- TRUE
} else {
# Jika bukan manager maka tetap tampilkan informasi
cat(paste0("Name: ", employees$Name[i],
", Position: ", employees$Position[i], "\n"))
}
# Menambah nilai indeks untuk berpindah ke baris berikutnya
i <- i + 1
}## Name: Bagas, Position: Staff
## Name: Joan, Position: Supervisor
## Name: Alya, Position: Staff
## Name: Dwi , Position: Manager (Stop here)
5 Loop Control
Loop control statements modify the normal execution of loops by stopping or skipping certain iterations.
5.1 Break
The break statement terminates a loop immediately when a specified condition is met.
# Perulangan untuk mengecek gaji setiap karyawan
for (i in 1:nrow(employees)) {
# Jika ditemukan gaji lebih dari 10000
if (employees$Salary[i] > 10000) {
# Tampilkan pesan bahwa perulangan dihentikan
cat("(Stopped because", employees$Name[i],
"has a salary above 10,000)\n")
# Menghentikan loop secara langsung
break
}
# Jika kondisi belum terpenuhi maka tampilkan data
cat(paste0("Name: ", employees$Name[i],
", Salary: ", employees$Salary[i], "\n"))
}## 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)
5.2 Continue
The next statement in R functions similarly to continue in other programming languages. It skips the current iteration and proceeds directly to the next iteration.
# Perulangan untuk mengecek performa setiap karyawan
for (i in 1:nrow(employees)) {
# Jika performa karyawan Average
if (employees$Performance[i] == "Average") {
# Tampilkan pesan bahwa data dilewati
cat("(Skipped because", employees$Name[i],
"has an Average performance)\n")
# Melewati iterasi saat ini dan lanjut ke iterasi berikutnya
next
}
# Jika bukan Average maka tampilkan nama dan performa
cat(paste0("Name: ", employees$Name[i],
", Performance: ", employees$Performance[i], "\n"))
}## Name: Bagas, Performance: Good
## Name: Joan, Performance: Very Good
## (Skipped because Alya has an Average performance)
## Name: Dwi, Performance: Good
## Name: Nabil, Performance: Very Good
6 Conclusion
This report demonstrates the practical implementation of syntax and control flow concepts in the R programming language. Through conditional statements and loop structures, programs can perform logical decision-making and repetitive operations when processing datasets.
The exercise illustrates how conditional statements determine employee bonuses based on performance, while loops allow the program to iterate through data records efficiently. Additionally, loop control statements such as break and next provide flexibility by allowing loops to terminate early or skip certain iterations.
Understanding syntax and control flow is essential for building structured and efficient programs, especially in data science where large datasets must be processed systematically.
References
- “Syntax and Control Flow,” Bookdown.
https://bookdown.org/dsciencelabs/data_science_programming/02-Syntax-and-Control-Flow.html