.x, not ., is recommended in ~ formula (#919)

* .x, not ., is recommended in ~ formula

* change . to .x to be consistent

* . refers to a list, while .x refers to a list element
This commit is contained in:
Mitsuo Shiota 2021-02-09 02:34:49 +09:00 committed by GitHub
parent f1805f2bfc
commit 35bca36e72
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 10 additions and 10 deletions

View File

@ -548,17 +548,17 @@ The syntax for creating an anonymous function in R is quite verbose so purrr pro
```{r}
models <- mtcars %>%
split(.$cyl) %>%
map(~lm(mpg ~ wt, data = .))
map(~lm(mpg ~ wt, data = .x))
```
Here I've used `.` as a pronoun: it refers to the current list element (in the same way that `i` referred to the current index in the for loop).
Here I've used `.x` as a pronoun: it refers to the current list element (in the same way that `i` referred to the current index in the for loop). `.x` in a one-sided formula corresponds to an argument in an anonymous function.
When you're looking at many models, you might want to extract a summary statistic like the $R^2$. To do that we need to first run `summary()` and then extract the component called `r.squared`. We could do that using the shorthand for anonymous functions:
```{r}
models %>%
map(summary) %>%
map_dbl(~.$r.squared)
map_dbl(~.x$r.squared)
```
But extracting named components is a common operation, so purrr provides an even shorter shortcut: you can use a string.
@ -717,7 +717,7 @@ What if you also want to vary the standard deviation? One way to do that would b
```{r}
sigma <- list(1, 5, 10)
seq_along(mu) %>%
map(~rnorm(5, mu[[.]], sigma[[.]])) %>%
map(~rnorm(5, mu[[.x]], sigma[[.x]])) %>%
str()
```
@ -848,13 +848,13 @@ x %>%
library(ggplot2)
plots <- mtcars %>%
split(.$cyl) %>%
map(~ggplot(., aes(mpg, wt)) + geom_point())
map(~ggplot(.x, aes(mpg, wt)) + geom_point())
paths <- stringr::str_c(names(plots), ".pdf")
pwalk(list(paths, plots), ggsave, path = tempdir())
```
`walk()`, `walk2()` and `pwalk()` all invisibly return `.x`, the first argument. This makes them suitable for use in the middle of pipelines.
`walk()`, `walk2()` and `pwalk()` all invisibly return `.`, the first argument. This makes them suitable for use in the middle of pipelines.
## Other patterns of for loops
@ -896,20 +896,20 @@ x <- sample(10)
x
x %>%
detect(~ . > 5)
detect(~ .x > 5)
x %>%
detect_index(~ . > 5)
detect_index(~ .x > 5)
```
`head_while()` and `tail_while()` take elements from the start or end of a vector while a predicate is true:
```{r}
x %>%
head_while(~ . > 5)
head_while(~ .x > 5)
x %>%
tail_while(~ . > 5)
tail_while(~ .x > 5)
```
### Reduce and accumulate