Partial function application allows you to modify a function by pre-filling some of the arguments. It is particularly useful in conjunction with functionals and other function operators.
partial(`_f`, ..., .env = parent.frame(), .lazy = TRUE)a function. For the output source to read well, this should be an
be a named function. This argument has the weird (non-syntactic) name
_f so it doesn't accidentally capture any argument names begining
with f.
named arguments to f that should be partially applied.
the environment of the created function. Defaults to
parent.frame and you should rarely need to modify this.
If TRUE arguments evaluated lazily, if FALSE,
evaluated when partial is called.
There are many ways to implement partial function application in R.
(see e.g. dots in https://github.com/crowding/vadr for another
approach.) This implementation is based on creating functions that are as
similar as possible to the anonymous function that'd you'd create by hand,
if you weren't using partial.
# Partial is designed to replace the use of anonymous functions for
# filling in function arguments. Instead of:
compact1 <- function(x) Filter(Negate(is.null), x)
# we can write:
compact2 <- partial(Filter, Negate(is.null))
# and the generated source code is very similar to what we made by hand
compact1
#> function (x)
#> Filter(Negate(is.null), x)
#> <environment: 0x58b5804563b8>
compact2
#> function (...)
#> Filter(Negate(is.null), ...)
#> <environment: 0x58b5804563b8>
# Note that the evaluation occurs "lazily" so that arguments will be
# repeatedly evaluated
f <- partial(runif, n = rpois(1, 5))
f
#> function (...)
#> runif(n = rpois(1, 5), ...)
#> <environment: 0x58b5804563b8>
f()
#> [1] 0.4800752 0.9200055 0.4007202 0.2131727
f()
#> [1] 0.05861411 0.99706914 0.14903547 0.51855664 0.84612005 0.71826972
# You can override this by saying .lazy = FALSE
f <- partial(runif, n = rpois(1, 5), .lazy = FALSE)
f
#> function (...)
#> runif(n = 3L, ...)
#> <environment: 0x58b5804563b8>
f()
#> [1] 0.54704337 0.83480182 0.02795603
f()
#> [1] 0.4693843 0.8056800 0.8140513
# This also means that partial works fine with functions that do
# non-standard evaluation
my_long_variable <- 1:10
plot2 <- partial(plot, my_long_variable)
plot2()
plot2(runif(10), type = "l")