Skip to content

Commit

Permalink
Update 4.iterations.md
Browse files Browse the repository at this point in the history
Ni
  • Loading branch information
MattBixley authored Feb 24, 2025
1 parent 12fd773 commit 4810d0f
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion docs/4.iterations.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ Consider the following loop:
for (i in 1:10) {
Ni <- i * 2
}

Ni
```

We constructed a loop to multiply each number by 2, but we only have 1 number as a result. This is because we assigned `Ni` with a new value with each iteration. To overcome this, we need to prepare an output vector that can store the result of each iteration.
Expand All @@ -77,6 +79,8 @@ We constructed a loop to multiply each number by 2, but we only have 1 number as
for (i in 1:10) {
Ni[i] <- i * 2
}

Ni
```

!!! warning "Thy shall not grow vectors"
Expand All @@ -91,6 +95,8 @@ We constructed a loop to multiply each number by 2, but we only have 1 number as
for (i in 1:10) {
Ni <- c(Ni, i * 2)
}

Ni
```

However, this kind of construct is not recommended for ***most*** use cases. If an iteration generates large number of elements, there might not be sufficient RAM to hold it and the entire R session will stall and terminate.
Expand Down Expand Up @@ -821,4 +827,4 @@ In older versions of R, there was a push to use `map_*()` (or the `apply()` fami
Generally, `map()` and `pmap()` is sufficient for a wide variety of scenarios. We advocate for its use given the advantage of cleaner and more readable code. Furthermore, most analyses can be simplified from a multi/nested list problem to solutions involving vectorisation or iteration of multiple equal-length vectors. It is really about being creative with data structures.
-->
-->

0 comments on commit 4810d0f

Please sign in to comment.