```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = T,
eval=T)
```
## `for`-loops
In R, we use loops whenever we need to run the same chunk of code across different units.
For example, we can use a loop to run a regression on different subsets of the data. Or when we have multiple Twitter accounts and want to run sentiment analysis for tweets posted by each of them.
The idea is simple: The loop 'loops' overcode 'for' a certain number of times. That means, it executes the same commands `i` times, varying only those elements that depend on `i`.
`for`-loops are probably the most common type of loop and are easily implemented in R
```{r}
for (i in 1:10){
print(i)
}
```
Note the structure:
`for (i in VECTOR){ do something with i }`
In each iteration, `i` takes a different value of the vector. We don't have to name this iterator `i` - `i` can be named anything!
```{r}
for (number in 1:10){
print(number)
}
```
The nice feature of loops is that they can reference values dependent on the iteration (as above with printing the current number in each iteration) and even use values from the previous iteration - if you want to try that there is an example at the end of this file.
When we don't just want to use loops for printing, there is another important feature:
If we use assignment operators within a loop (e.g. `object <- element[i]`), our loop would over-write the output each time we run the code. So we need to make assignment dependent on the iteration as well.
Because of that, we first create an empty vector into which we can store the output and then always assign our result to the `i`-th value of this vector:
```{r}
values <- ""
for (i in 1:10){
values[i] <- i
}
values
```
This is it - you know enough to scrape!
Still, if you want to see something extra, here is an example how to use values from previous iterations. You might have heard of the Fibonacci sequence - a sequence of numbers where each number is the sum of the two preceding numbers.
This is perfect as an example: we can get the first 40 terms in the Fibonacci sequence () using a `for`-loop that references previous values.
```{r}
fib <- c(0, 1, rep(NA, 38))
for(i in 3:40) {
fib[i] <- fib[i-1] + fib[i-2]
}
fib
```