6 Loops
If you want to repeat a process many times you will need to create a loop:
6.1 Basic for Loop structure
6.2 Looping through a vector
## [1] "a"
## [1] "b"
## [1] "c"
6.3 Creating a List in a Loop
newList <- list() # An empty List
for (x in 1:5) {
newList[[x]] = x^2 # Inserts an element into the List
}
newList[[3]] ## [1] 9
6.4 Looping with apply functions
An alternative to using ‘for’ loops is to use the apply functions. This means turning process into a function and then applying the function to a vector/matrix/list:
loopvector <- c("a","b","c")
print_list <- function(x) {
print(x)
}
test <- sapply(loopvector, print_list)## [1] "a"
## [1] "b"
## [1] "c"
There are various types of apply function.
sapply will usually return output as a vector.
lapply will usually return output in a list.