Purrr ~ 操作员在哪里记录?

Where is the Purrr ~ operator documented?

我搜索了 ??"~",但这只指向 rlang::env_bind(大概是 %<~%)和 base::~。在 RStudio 中,如何找到 Purrr 的 ~ 文档?例如,如果我忘记了如何将 ~ 与两个输入一起使用,我应该在哪里查找?

当你在 purrr 函数的上下文中使用 ~ 时,它会被传递给 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,它有一些很好的例子,本章继续这些想法。

AdvanceR 给出了很好的解释(link 在另一个答案中给出)。 purrr cheatsheat 第一页左下角也有一个简短的描述(使用示例)。

使用 twiddle ~ 的多个参数可以在不同函数中给出的 purrr 文档中看到。例如map 参见参数说明,其中指出

.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.


此外,R 在其最新版本 (4.1.0) 中也有 started 类似的 shorthand 函数符号

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

这个 shorthand 符号也可以在 tidyverse 之外的函数中提供有用的,与 twiddle 的唯一区别是这里的参数默认情况下没有命名。但同样,当一个不可见函数要在另一个函数中使用时,这种非默认命名也可能被证明是有用的,并且 twiddle 表示法风格在这种情况下将不起作用。