Looping over a list is similar to looping over a vector: the loop variable receives each element of the list.
basket <- list(
Basket = c("Apple", "Orange", "Passion fruit", "Banana"),
Money = c(10, 12, 15),
Purchase = FALSE
)
for (item in basket) {
print(item)
}## [1] "Apple" "Orange" "Passion fruit" "Banana"
## [1] 10 12 15
## [1] FALSE
If you need both names and values, iterate over
names():
## Basket :
## [1] "Apple" "Orange" "Passion fruit" "Banana"
## Money :
## [1] 10 12 15
## Purchase :
## [1] FALSE
A matrix has rows and columns, so nested loops are common.
mat <- matrix(seq(10, 21, by = 1), nrow = 6, ncol = 2)
for (r in seq_len(nrow(mat))) {
for (c in seq_len(ncol(mat))) {
cat("Row", r, "and column", c, "has value", mat[r, c], "\n")
}
}## Row 1 and column 1 has value 10
## Row 1 and column 2 has value 16
## Row 2 and column 1 has value 11
## Row 2 and column 2 has value 17
## Row 3 and column 1 has value 12
## Row 3 and column 2 has value 18
## Row 4 and column 1 has value 13
## Row 4 and column 2 has value 19
## Row 5 and column 1 has value 14
## Row 5 and column 2 has value 20
## Row 6 and column 1 has value 15
## Row 6 and column 2 has value 21
Notes: - seq_len(n) is a safe way to generate
1:n-style sequences (it works well even when n
can be 0). - cat() produces cleaner console output than
print(paste(...)) for simple messages. ```
A work by Gianluca Sottile
gianluca.sottile@unipa.it