Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tilde Dot in R (~.)

Tags:

r

dplyr

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

like image 757
bg47 Avatar asked Jan 01 '23 15:01

bg47


1 Answers

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.

like image 80
Artem Sokolov Avatar answered Jan 05 '23 03:01

Artem Sokolov