What does the "~" operator mean in tidyverse context?

Asked

Viewed 50 times

3

Suppose 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 role to follow:

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 take out 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.

  • Meaning the use of the operator ~ within codes of tidyverse?

1 answer

0


The operator ~ in the context tidyverse is a proxy of the anonymous function. Instead of writing:

function(k) {is_weakly_greater_than(e1 = k, e2 = 40)}

I can replace function(k) {...} for ~. Thus:

~ is_weakly_greater_than(e1 = ., e2 = 40))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.