I'm going through the examples of map()
from 'R For Data Science'.
One example is:
library(dplyr)
library(purrr)
df <- tibble(
a = rnorm(10),
b = rnorm(10),
c = rnorm(10),
d = rnorm(10)
)
df
#> # A tibble: 10 x 4
#> a b c d
#> <dbl> <dbl> <dbl> <dbl>
#> 1 -0.570 1.48 2.37 1.60
#> 2 0.122 2.08 0.222 0.0338
#> 3 -0.890 0.429 -1.75 -1.48
#> 4 0.334 0.854 0.849 -0.525
#> 5 1.22 -0.378 -1.00 -0.147
#> 6 -1.04 -0.427 -1.18 0.907
#> 7 -0.392 0.102 0.0951 0.842
#> 8 0.893 0.932 0.620 -0.911
#> 9 1.00 0.616 -0.937 -0.0286
#> 10 0.190 1.12 -1.02 1.45
In the map_dbl() below, I don't need to add a tilde before the function map_dbl(~ mean)
and I don't have to put .
df %>% map_dbl(mean)
#> a b c d
#> 0.08714704 0.68069227 -0.17382734 0.17470388
Whereas, in the example below, I do have to put the ~
before the .f and I also have to specify data = .
models <- mtcars %>%
split(.$cyl) %>%
map(~ lm(mpg ~ wt, data = .))
models
I've tried reading previous answers, eg What is meaning of first tilde in purrr::map, but I'm still unsure as to the exact difference of when I need to use the tilde and .
Would perhaps the easiest way be for me to just always include those two things, even if they aren't strictly necessary?