Anonymous functions and shortcuts

Anonymous functions

map_dbl(.x=mtcars, .f=function(x) mean(x, na.rm = TRUE)) |> 
  head()
#>        mpg        cyl       disp         hp       drat         wt 
#>  20.090625   6.187500 230.721875 146.687500   3.596563   3.217250
  • the “twiddle” uses a twiddle ~ to set a formula
  • can use .x to reference the input map(.x = ..., .f = )
map_dbl(.x=mtcars,  .f=~mean(.x, na.rm = TRUE))
  • can be simplified further as
map_dbl(.x=mtcars, .f=mean, na.rm = TRUE)
#>        mpg        cyl       disp         hp       drat         wt       qsec 
#>  20.090625   6.187500 230.721875 146.687500   3.596563   3.217250  17.848750 
#>         vs         am       gear       carb 
#>   0.437500   0.406250   3.687500   2.812500
  • what happens when we try a handful of variants of the task at hand? (how many unique values are there for each variable?)

Note that .x is the name of the first argument in map() (.f is the name of the second argument).

# the task
map_dbl(mtcars, function(x) length(unique(x)))
#>  mpg  cyl disp   hp drat   wt qsec   vs   am gear carb 
#>   25    3   27   22   22   29   30    2    2    3    6
map_dbl(mtcars, function(unicorn) length(unique(unicorn)))
#>  mpg  cyl disp   hp drat   wt qsec   vs   am gear carb 
#>   25    3   27   22   22   29   30    2    2    3    6
map_dbl(mtcars, ~length(unique(.x)))
#>  mpg  cyl disp   hp drat   wt qsec   vs   am gear carb 
#>   25    3   27   22   22   29   30    2    2    3    6
map_dbl(mtcars, ~length(unique(..1)))
#>  mpg  cyl disp   hp drat   wt qsec   vs   am gear carb 
#>   25    3   27   22   22   29   30    2    2    3    6
map_dbl(mtcars, ~length(unique(.)))
#>  mpg  cyl disp   hp drat   wt qsec   vs   am gear carb 
#>   25    3   27   22   22   29   30    2    2    3    6

# not the task
map_dbl(mtcars, length)
#>  mpg  cyl disp   hp drat   wt qsec   vs   am gear carb 
#>   32   32   32   32   32   32   32   32   32   32   32
map_dbl(mtcars, length(unique))
#>    mpg    cyl   disp     hp   drat     wt   qsec     vs     am   gear   carb 
#>  21.00   6.00 160.00 110.00   3.90   2.62  16.46   0.00   1.00   4.00   4.00
map_dbl(mtcars, 1)
#>    mpg    cyl   disp     hp   drat     wt   qsec     vs     am   gear   carb 
#>  21.00   6.00 160.00 110.00   3.90   2.62  16.46   0.00   1.00   4.00   4.00
#error
map_dbl(mtcars, length(unique()))
#> Error in unique.default(): argument "x" is missing, with no default
map_dbl(mtcars, ~length(unique(x)))
#> Error in `map_dbl()`:
#> ℹ In index: 1.
#> ℹ With name: mpg.
#> Caused by error in `.f()`:
#> ! object 'x' not found