Consistently style for loops

This commit is contained in:
Hadley Wickham 2022-12-06 12:59:03 -06:00
parent cf823b61fb
commit fc5c2044e8
1 changed files with 7 additions and 7 deletions

View File

@ -19,7 +19,7 @@ After you read this book you'll learn other approaches to the same problems usin
You'll certainly encounter these other approaches when you start reading R code written by other people, particularly if you're using StackOverflow.
It's 100% okay to write code that uses a mix of approaches, and don't let anyone tell you otherwise!
In this chapter, we'll focus on four big topics: subsetting with `[`, subsetting with `[[` and `$`, the apply family of functions, and for loops.
In this chapter, we'll focus on four big topics: subsetting with `[`, subsetting with `[[` and `$`, the apply family of functions, and `for` loops.
To finish off, we'll briefly discuss two important plotting functions.
### Prerequisites
@ -446,9 +446,9 @@ This rarely comes up in data science because we usually work with data frames an
## For loops
For loops are the fundamental building block of iteration that both the apply and map families use under the hood.
For loops are powerful and general tools that are important to learn as you become a more experienced R programmer.
The basic structure of a for loop looks like this:
`for` loops are the fundamental building block of iteration that both the apply and map families use under the hood.
`for` loops are powerful and general tools that are important to learn as you become a more experienced R programmer.
The basic structure of a `for` loop looks like this:
```{r}
#| eval: false
@ -457,7 +457,7 @@ for (element in vector) {
}
```
The most straightforward use of `for()` loops is to achieve the same affect as `walk()`: call some function with a side-effect on each element of a list.
The most straightforward use of `for` loops is to achieve the same affect as `walk()`: call some function with a side-effect on each element of a list.
For example, in @sec-save-database instead of using walk:
```{r}
@ -465,7 +465,7 @@ For example, in @sec-save-database instead of using walk:
paths |> walk(append_file)
```
We could have used a for loop:
We could have used a `for` loop:
```{r}
#| eval: false
@ -474,7 +474,7 @@ for (path in paths) {
}
```
Things get a little trickier if you want to save the output of the for-loop, for example reading all of the excel files in a directory like we did in @sec-iteration:
Things get a little trickier if you want to save the output of the `for` loop, for example reading all of the excel files in a directory like we did in @sec-iteration:
```{r}
paths <- dir("data/gapminder", pattern = "\\.xlsx$", full.names = TRUE)