View source: R/adverb-partial.R
partial | R Documentation |
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 = deprecated(),
.lazy = deprecated(),
.first = deprecated()
)
partial()
creates a function that takes ...
arguments. Unlike
compose()
and other function operators like negate()
, it
doesn't reuse the function signature of .f
. This is because
partial()
explicitly supports NSE functions that use
substitute()
on their arguments. The only way to support those is
to forward arguments through dots.
Other unsupported patterns:
It is not possible to call partial()
repeatedly on the same
argument to pre-fill it with a different expression.
It is not possible to refer to other arguments in pre-filled argument.
A function that takes the same arguments as .f
, but returns
a different value, as described above.
This function is called an adverb because it modifies the effect of a function (a verb). If you'd like to include a function created an adverb in a package, be sure to read faq-adverbs-export.
Other adverbs:
auto_browse()
,
compose()
,
insistently()
,
negate()
,
possibly()
,
quietly()
,
safely()
,
slowly()
# Partial is designed to replace the use of anonymous functions for
# filling in function arguments. Instead of:
compact1 <- function(x) discard(x, is.null)
# we can write:
compact2 <- partial(discard, .p = is.null)
# 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")
# Note that you currently can't partialise arguments multiple times:
my_mean <- partial(mean, na.rm = TRUE)
my_mean <- partial(my_mean, na.rm = FALSE)
try(my_mean(1:10))
# The evaluation of arguments normally occurs "lazily". Concretely,
# this means that arguments are repeatedly evaluated across invocations:
f <- partial(runif, n = rpois(1, 5))
f
f()
f()
# You can unquote an argument to fix it to a particular value.
# Unquoted arguments are evaluated only once when the function is created:
f <- partial(runif, n = !!rpois(1, 5))
f
f()
f()
# By default, partialised arguments are passed before new ones:
my_list <- partial(list, 1, 2)
my_list("foo")
# Control the position of these arguments by passing an empty
# `... = ` argument:
my_list <- partial(list, 1, ... = , 2)
my_list("foo")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.