14 Loops

14.1 for loop

for (i in c("a", "b", "c")){
  print(paste("This iteration represents", i))
}
## [1] "This iteration represents a"
## [1] "This iteration represents b"
## [1] "This iteration represents c"

14.2 apply family

These functions also perform loops but are a little bit more specific in how the loop is performed or how the output is returned relative to the for loop.

14.2.1 apply

The iris data set will be used as an example. The Species column will be dropped from iris for this exercies and this object will be stored as iris.df.

iris.df <- head(iris[, names(iris) != "Species"])

Apply a function by row. In this case, sum() by row.

apply(iris.df, 1, sum)
##    1    2    3    4    5    6 
## 10.2  9.5  9.4  9.4 10.2 11.4

Apply a function by column. In this case, sum() by column.

apply(iris.df, 2, sum)
## Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
##         29.7         20.3          8.7          1.4

14.2.2 lapply

lapply() loops through a vector or list and returns a list, hence the ā€œLā€ in lapply(). Compare the output below to the for loop example. lapply() returns a list of strings that were printed in the for loop example.

lapply(c("a", "b", "c"), function(i) {
  paste("This iteration represents", i)
})
## [[1]]
## [1] "This iteration represents a"
## 
## [[2]]
## [1] "This iteration represents b"
## 
## [[3]]
## [1] "This iteration represents c"

Now compare the apply() example summing rows above to this lapply() call

lapply(1:nrow(iris.df), function(i) {
  sum(iris.df[i, ])
})
## [[1]]
## [1] 10.2
## 
## [[2]]
## [1] 9.5
## 
## [[3]]
## [1] 9.4
## 
## [[4]]
## [1] 9.4
## 
## [[5]]
## [1] 10.2
## 
## [[6]]
## [1] 11.4

Now compare the apply() example summing columns above to this lapply() call.

lapply(1:ncol(iris.df), function(i) {
  sum(iris.df[, i])
})
## [[1]]
## [1] 29.7
## 
## [[2]]
## [1] 20.3
## 
## [[3]]
## [1] 8.7
## 
## [[4]]
## [1] 1.4

14.2.3 sapply

sapply() loops through a vector or list and returns a vector. Compare the output below to the similar for() loop and lapply() examples. sapply() returns a vector of strings that were printed in the for() loop example and the strings returned as a list in the lapply() example.

sapply(c("a", "b", "c"), function(i) {
  paste("This iteration represents", i)
})
##                             a                             b 
## "This iteration represents a" "This iteration represents b" 
##                             c 
## "This iteration represents c"

Now compare the apply() and lapply() examples summing rows above to this sapply() call.

sapply(1:nrow(iris.df), function(i) {
  sum(iris.df[i, ])
})
## [1] 10.2  9.5  9.4  9.4 10.2 11.4

Now compare the apply() and lapply() examples summing columns above to this sapply() call.

sapply(1:ncol(iris.df), function(i) {
  sum(iris.df[, i])
})
## [1] 29.7 20.3  8.7  1.4