I'm going over looping with tidyverse and purrr using Hadley's R4DS book and am a little confused as to the exact usage of the tilde ~ symbol and period symbol.
So when writing for loops, or using map(), instead of writing out function(), it appears you can use the tilde symbol instead ~.
Does this only apply to for loops?
so as below...
models <- mtcars %>%
split(.$cyl) %>%
map(~lm(mpg ~ wt, data = .))
Additionally, the period i was told can be used "to refer to the current list element". But I am confused what that means. Does that mean, that only when looping, the period means it refers to the element in the list that is being looped over? How is it different from piping? When you pipe, you are piping the result of one line to the next line of code.
So in the case above, mtcars is piped to the second line with split() but a period is used. Why?
The case below sums up my confusion:
x <- c(1:10)
detect(x, ~.x > 5)
using the detect function, which finds the first match, I thought i could just use
detect(x, x >5)
but I get an error saying x >5 is not a function. So i add a tilde
detect(x, ~ x > 5)
and get an error sayingt it expects a single TRUE or FALSE, not 10. So if you add a period
detect(x, ~.x >5)
suddenly it works as looping. So what is the relation/ usage of ~ and . here and how does . compare to simple piping?