R 中的波浪号 (~.) [英] Tilde Dot in R (~.)

查看:165
本文介绍了R 中的波浪号 (~.)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下 R 中的波浪号 (~.)?我已经看到一些关于它的帖子.我知道波浪号用于公式,指定自变量和因变量.而且,我知道点用于表示所有其他变量.更具体地说,有人可以解释一下这个例子中的波浪号吗?

x <- 样本(10)×%>%检测(~.> 5)

谢谢

解决方案

正如 MrFlick 所指出的,这是两个独立的操作符.它们一起提供了一种特殊的机制,允许 tidyverse 包动态构建 lambda 函数.这在 ?purrr::as_mapper<中有最好的描述/代码>.具体来说,

<块引用>

如果一个公式,例如~ .x + 2,它被转换为一个函数.引用参数的三种方式:

  • 对于单参数函数,使用 .

  • 对于两个参数的函数,使用 .x 和 .y

  • 要获得更多参数,请使用 ..1、..2、..3 等

使用您的示例:

purrr::as_mapper( ~. > 5 )# <拉姆达># 函数 (..., .x = ..1, .y = ..2, . = ..1)# .>5# attr(,类")# [1] "rlang_lambda_function";

创建一个函数,该函数返回一个逻辑值,指示函数的参数是否大于 5.purrr::detect() 内部生成这个函数,然后用它来遍历输入向量x.最终结果是 x 中满足大于 5"的第一个元素.约束.

正如 Konrad 所指出的,这种机制是 tidyverse 特有的,一般来说不起作用.在 tidyverse 之外,此语法的行为在相关问题中进行了解释.>

Can anyone explain the tilde dot (~.) in R? I have seen some posts about it already. I know the tilde is used for formulas, specifying the independent and dependent variables. And, I know that the dot is used to indicate all other variables. More specifically, can someone explain the tilde dot in this example?

x <- sample(10)
x %>%
  detect(~. > 5)

Thanks

解决方案

As MrFlick pointed out, these are two separate operators. Together, they provide a special mechanism that allows tidyverse packages to construct lambda functions on the fly. This is best described in ?purrr::as_mapper. Specifically,

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

Using your example:

purrr::as_mapper( ~. > 5 )
# <lambda>
# function (..., .x = ..1, .y = ..2, . = ..1)
# . > 5
# attr(,"class")
# [1] "rlang_lambda_function"

creates a function that returns a logical value indicating whether the argument of the function is greater than 5. purrr::detect() generates this function internally and then uses it to traverse the input vector x. The final result is the first element of x that satisfies the "greater than 5" constraint.

As pointed out by Konrad, this mechanism is specific to tidyverse and does not work in general. Outside of tidyverse, the behavior of this syntax is explained in a related question.

这篇关于R 中的波浪号 (~.)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆