neves
neves

Reputation: 846

What is the meaning of the `~` operator in the tidyverse context?

Assume the data set below:

df_1 <- structure(list(var_1 = c(42.0324095338583, 86.828490421176, 42.4499513395131, 
87.8373390808702, 69.4962524808943), var_2 = c(52.6775231584907, 
60.7429852150381, 23.1536079756916, 89.0404256992042, 40.8967914432287
), var_3 = c(53.2254045270383, 99.7671523876488, 55.2181884087622, 
97.3904117196798, 63.9911676943302), var_4 = c(77.9183112829924, 
53.8156733289361, 71.4701929315925, 70.3330857120454, 24.3069419451058
), var_5 = c(48.498358130455, 86.109549254179, 45.0998894125223, 
61.7115858010948, 39.3580442667007), var_6 = c(43.4050587192178, 
32.7955435216427, 46.6158176586032, 43.4641770273447, 49.2192720063031
), groups = structure(c(1L, 2L, 2L, 2L, 2L), .Label = c("1", 
"2", "3"), class = "factor")), row.names = c(NA, 5L), class = "data.frame")

And the following function:

library(tidyverse)
library(magrittr)

df_1 %>% 
  filter(
    across(.cols = is.numeric, .fns = ~ is_weakly_greater_than(e1 = ., e2 = 40))
  )

#     var_1    var_2    var_3    var_4    var_5    var_6 groups
#1 42.03241 52.67752 53.22540 77.91831 48.49836 43.40506      1
#2 87.83734 89.04043 97.39041 70.33309 61.71159 43.46418      2

It works normally. But, just remove the ~ operator:

df_1 %>% 
  filter(
    across(.cols = is.numeric, .fns = is_weakly_greater_than(e1 = ., e2 = 40))
  )

Error: across() must only be used inside dplyr verbs.

Upvotes: 1

Views: 200

Answers (2)

David T
David T

Reputation: 2143

Most commonly, it's a shorthand way of writing an anonymous function.

map_dbl(HEIGHT, ~ sum(.x, 5))

is the same as

map_dbl(HEIGHT, function(.x){sum(.x, 5))

It has other meanings in other contexts. E.g., at the R> prompt, type

? case_when 

to see how it uses ~.

Upvotes: 5

Ronak Shah
Ronak Shah

Reputation: 388862

There are multiple ways you can apply a function in dplyr verbs.

Using the function as it is :

library(dplyr)
mtcars %>% mutate_if(is.numeric, sqrt)

Using formula interface i.e ~

mtcars %>% mutate_if(is.numeric, ~sqrt(.))

Using anonymous function -

mtcars %>% mutate_if(is.numeric, function(x) sqrt(x))

When you are using ~, you are notifying that you are going to use the formula interface of the function.

Obviously, sqrt is just an example and you can apply more complicated functions using this.

Upvotes: 3

Related Questions