A for loop repeats the same task for each value in a finite sequence. In R, it replaces copied-and-pasted code with one maintainable block, reducing repetition and opportunities for error. section 13.6.1
Use a for loop when an analysis repeats a finite task:
- Choose a vector of iteration values, such as 1:5 or four selected NBA seasons. section 13.6.1 section 13.6.2
- Place the repeated operation inside curly brackets. section 13.6.1
- Let the index take each value in turn, then update the operation once when requirements change. section 13.6.1
Creating four Lorenz curves
After reshaping win-share data into four season columns, a loop selects each column and creates a Lorenz curve: par(mfrow = c(2, 2)) loop.vector <- 1:4 for (i in loop.vector) { x <- ws9194[, i] plot(Lc(x), col = "red", lwd = 2, main = paste0("Lorenz Curve\n", "199", i), xlab = "Win Share Distribution", ylab = "Percentage of NBA Players") } The same plotting instructions produce four season-specific charts without four copied code blocks. section 13.6.2
for (i in 1:5) {
print(i * 2)
}
## [1] 2
## [1] 4
## [1] 6
## [1] 8
## [1] 10
A minimal loop shows the index changing from 1 through 5 and printing each value multiplied by two. section 13.6.1


























