R中的Tilde点(〜。) [英] Tilde Dot in R (~.)

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

问题描述

有人可以解释R中的波浪点(〜。)吗?我已经看过一些有关它的文章。我知道代字号用于公式,指定自变量和因变量。而且,我知道该点用于指示所有其他变量。更具体地说,有人可以在此示例中解释波浪点吗?

  x<-sample(10)
x% >%
detect(〜。> 5)

谢谢

解决方案

正如MrFlick指出的那样,这是两个单独的运算符。它们共同提供了一种特殊的机制,允许tidyverse程序包动态构建 lambda函数。最好在 ?purrr中进行描述: :as_mapper 。具体来说,


如果使用公式,例如〜.x + 2,它将转换为函数。引用参数的方法有以下三种:



  • 对于单个参数函数,请使用。



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



  • 对于更多的参数,请使用..1,.. 2,.. 3等




使用您的示例:

  purrr :: as_mapper(〜。> 5)
#< lambda>
#函数(...,.x = ..1,.y = ..2,。= ..1)
#。 > 5
#attr(, class)
#[1] rlang_lambda_function

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


如Konrad所指出的那样,该机制特定于tidyverse,并且 not 通常不会起作用。在tidyverse之外,该语法的行为在相关问题中进行了说明。。 p>

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中的Tilde点(〜。)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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