Tilde Dot in R (~.)

后端 未结 1 1659
一个人的身影
一个人的身影 2020-12-03 13:08

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 variable

相关标签:
1条回答
  • 2020-12-03 13:38

    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.

    0 讨论(0)
提交回复
热议问题