liveBook · Manning

Loop

As explained in Statistics Slam Dunk

A for loop is a control-flow construct that executes a block of code once for each value in a finite sequence or iterable.

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

How Statistics Slam Dunk covers it

How deep it goes
Defines loop syntax, explains index replacement, and demonstrates a multi-plot workflow without covering advanced loop patterns.
Examples
Demonstrates multiplication across 1:5 and Lorenz curves across four NBA seasons.
What you can do after
Apply it via R to replace repeated code with one maintainable operation.
How it connects
Connects for loops to vectors, Lorenz curves, Gini coefficients, data frames, and user-defined functions.

Also explained in

Compare how 27 books explain loop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Statistics Slam Dunk. The section links point to the parts of the book it draws on.