6

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

zx8754
  • 52,746
  • 12
  • 114
  • 209
bg47
  • 63
  • 1
  • 4
  • might be worth some time to read R manual pages as noted in the answer. it's explained really clearly in there. – hrbrmstr Nov 05 '18 at 18:33
  • 3
    And it's important to know that tilde-dot isn't a compound operator or anything. They are two separate things. You could have also done `detect(~5 < .)`. They each are doing something different. You are making a formula (with `~`) that uses a special variable (named `.`) which some function interpret as a creating a lambda function (but this is true mostly just for "tidyverse" functions). – MrFlick Nov 05 '18 at 18:48

1 Answers1

11

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.

Community
  • 1
  • 1
Artem Sokolov
  • 13,196
  • 4
  • 43
  • 74
  • 10
    +1. It’s worth highlighting that this mention does *not* work in general, it only works with specific functions (unlike anonymous functions, which work everywhere). – Konrad Rudolph Nov 05 '18 at 18:25