0
library(tidyverse)
df <- tibble(col1 = c("A", "B", "C"), col2 = c(NA, Inf, 5))
#> # A tibble: 3 x 2
#>   col1   col2
#>   <chr> <dbl>
#> 1 A        NA
#> 2 B       Inf
#> 3 C         5

What is the role of the ~ tilde in line #3 in the code chunk below? It is my understanding from this SO answer that dplyr reserves the use of ~ for non-standard evaluation (NSE).

I've come across one article that has made any sense in the world of NSE. Here's hoping the ~ serves a different role (other than NSE) in my code chunk below.

df %>% 
  replace(is.na(.), 0) %>% 
  mutate_if(is.numeric, list(~na_if(abs(.), Inf))) %>%  # line 3
  replace(is.na(.), 1)
#> # A tibble: 3 x 2
#>   col1   col2
#>   <chr> <dbl>
#> 1 A         0
#> 2 B         1
#> 3 C         5
Display name
  • 4,153
  • 5
  • 27
  • 75
  • 4
    Here, it is used as a anonymous function call i.e. `~ .` would be `function(x) x` – akrun Nov 13 '19 at 21:18
  • 3
    It's a shorthand for creating an anonymous function. Unless there's more to the question that I'm missing...? – camille Nov 13 '19 at 21:18
  • 4
    The tilde makes a formula, and since the argument in mutate is passed to `as_function`, the formula is converted to a function – IceCreamToucan Nov 13 '19 at 21:21
  • 2
    That is a form of nonstandard evaluation. The `?mutate_if` help page describes the `fun` argument as *"A function `fun`, a quosure style lambda `~ fun(.)` or a list of either form."* *lambda* is just a computer-sciency term for "anonymous function". – Gregor Thomas Nov 13 '19 at 21:22
  • 1
    Arguably a dupe: https://stackoverflow.com/q/58377184/5325862 – camille Nov 13 '19 at 21:24
  • I'll have to search around because I have no clue what an "anonymous function call" is. I'm looking for the not-a-computer-scientist answer. Sorry to sound so silly. – Display name Nov 13 '19 at 21:26
  • 4
    Normally you would give your function a name e.g. when you run `myfun <- function(x) x + 2` you create a function the name `myfun`. But [anonymous functions](https://en.wikipedia.org/wiki/Anonymous_function) are just created and used without ever being named, so are called "anonymous" due to the lack of name. This is a non-technical answer and "name" is not a real concept in R, at least not in the way I'm using it. – IceCreamToucan Nov 13 '19 at 21:29
  • 1
    Another example of what the tidle means here: https://stackoverflow.com/questions/44834446/what-is-meaning-of-first-tilde-in-purrrmap `dplyr` uses the same methods as `purr` to turn the formulas into functions – MrFlick Nov 13 '19 at 21:35
  • 1
    Basically they are doing `rlang::as_function` which was brought up in one of your previous questions: https://stackoverflow.com/questions/56532119/dplyr-piping-data-difference-between-and-x – MrFlick Nov 13 '19 at 21:37

0 Answers0