Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the Purrr ~ operator documented?

Tags:

r

lambda

purrr

I searched for ??"~" but this only points me to rlang::env_bind (presumably, %<~%) and base::~. Within RStudio, how can I find Purrr's ~'s documentation? For example, if I forgot how to use ~ with two inputs, where do I look?

like image 843
J. Mini Avatar asked May 21 '21 19:05

J. Mini


2 Answers

There is a good explanation given AdvanceR (link given in another answer). There is also a short description (usage example) given in purrr cheatsheat first page bottom left.

enter image description here

The usage of multiple arguments with twiddle ~ may be seen at with documentation of purrr given in its different functions. e.g. map see argument description which states that

.f A function, formula, or vector (not necessarily atomic). If a function, it is used as is. If a formula, e.g. ~ .x + 2, it is converted to a function. There are three ways to refer to the arguments: For a single argument function, use .

For a two argument function, use .x and .y

For more arguments, use ..1, ..2, ..3 etc

This syntax allows you to create very compact anonymous functions.


Moreover, R in its newest version (4.1.0) has also started similar kind of shorthand notation of functions

R now provides a shorthand notation for creating functions, e.g. \(x) x + 1 is parsed as function(x) x + 1.

This shorthand notation may also provide useful in functions outside tidyverse, with only differentiation from twiddle being that here arguments are not named by default. But again, this non-default naming may also be proved useful when one invisible function is to be used inside another and twiddle style of notation will not work in that case.

like image 90
AnilGoyal Avatar answered Oct 08 '22 08:10

AnilGoyal


When you use ~ within the context of purrr functions, it will be passed to the as_mapper() function, which in turn passes on to the as_function() function from rlang. These help files have a very basic bit of what is needed to use this. This is further documented in the Advanced R Book Chapter 9, Section 9.22, which has a few good examples, and this chapter goes on to continue those ideas.

like image 32
Michael Barrowman Avatar answered Oct 08 '22 09:10

Michael Barrowman