Travis-CI Build Status codecov CRAN_Status_Badge

nofrills

Low-Cost Anonymous Functions

Overview

nofrills is a lightweight R package that provides fn(), a more powerful variation of function() that:

Installation

install.packages("nofrills")

Alternatively, install the development version from GitHub:

# install.packages("devtools")
devtools::install_github("egnha/nofrills")

Usage

Same syntax as function() but shorter

fn(x ~ x + 1)
#> function (x) 
#> x + 1

fn(x, y ~ x + y)
#> function (x, y) 
#> x + y

fn(x, y = 2 ~ x + y)
#> function (x, y = 2) 
#> x + y

fn(x, y = 1, ... ~ log(x + y, ...))
#> function (x, y = 1, ...) 
#> log(x + y, ...)

# the only exception, cf. alist()
fn(x, ... = , y ~ log(x + y, ...))
#> function (x, ..., y) 
#> log(x + y, ...)

fn(~ NA)
#> function () 
#> NA

Supports quasiquotation

Unquoting values

z <- 0

fn(x, y = !! z ~ x + y)
#> function (x, y = 0) 
#> x + y

fn(x ~ x > !! z)
#> function (x) 
#> x > 0

Unquoting argument names

arg <- "y"

fn(x, !! arg := 0 ~ x + !! as.name(arg))
#> function (x, y = 0) 
#> x + y

Splicing in argument lists

args <- alist(x, y = 0)

fn(!!! args, ~ x + y)  # note the one-sided formula
#> function (x, y = 0) 
#> x + y

Literal unquoting via QUQ(), QUQS(), QUQE()

library(dplyr, warn.conflicts = FALSE)

summariser <- quote(mean)

my_summarise <- fn(df, ... ~ {
  group_by <- quos(...)
  df %>%
    group_by(QUQS(group_by)) %>%
    summarise(a = UQ(summariser)(a))
})

my_summarise
#> function (df, ...) 
#> {
#>     group_by <- quos(...)
#>     df %>% group_by(UQS(group_by)) %>% summarise(a = mean(a))
#> }

(Source: Programming with dplyr)

Pure functions via quasiquotation

Functions in R are generally impure, i.e., the return value of a function will not in general be determined by the value of its inputs alone. This is because a function may depend on mutable objects in its lexical scope. Normally this isn’t an issue. But if you are working interactively and sourcing files into the global environment, say, or using a notebook interface (like Jupyter or R Notebook), it can be tricky to ensure that you haven’t unwittingly mutated an object that an earlier function depends upon.

fn() enables you to write pure functions by using quasiquotation to eliminate such indeterminacy.

Alternatives to nofrills

Here are some alternative anonymous-function constructors (which don’t support quasiquotation), ordered by increasing concision and specialization:

Acknowledgement

The rlang package by Lionel Henry and Hadley Wickham makes nofrills possible. Crucially, rlang provides the engine for quasiquotation and expression capture.

License

MIT Copyright © 2017 Eugene Ha