Defer {grandR} | R Documentation |
Defer calling a function
Description
This generates a function with one mandatory parameter (and additional optional parameters)
that, when called, (i) also receives the parameters given when calling Defer
, and (ii)
after calling it each element of the add
list is appended by +
. When no optional parameters
are given, the result is cached.
Usage
Defer(FUN, ..., add = NULL, cache = TRUE, width.height = NULL)
Arguments
FUN |
the function to be deferred |
... |
additional parameters to be used when the deferred function is called |
add |
list containing additional elements to be added |
cache |
use caching mechanism |
width.height |
a vector containing the desired width and height (not checked!) |
Details
The following expressions are very similar: f <- function(d) Heavy.function(d)
and f <- Defer(Heavy.function)
. In
both cases, you get a function f
that you can call for some d
, which in turn calls Heavy.function
. The only
difference is that in the second case, the result is cached: Heavy.function
is called only once when first calling f
,
if f
is called a second time, the previous result is returned. This makes sense if the parameter d
is constant (like a grandR object)
and if Heavy.function
is deterministic.
If additional parameters are provided to f
, caching is disabled. If any of these additional parameters has the same name as the parameters
given to Defer()
, the parameters given to Defer()
are overwritten. Be careful if Heavy.function
is not deterministic (see examples).
Use case scenario: You want to produce a heatmap from a grandR object to be used as plot.static
in the shiny web interface.
PlotHeatmap
takes some time, and the resulting object is pretty large in memory. Saving the heatmap object to disk is very
inefficient (the Rdata file will be huge, especially with many heatmaps). Deferring the call without caching also is bad, because whenever
the user clicks onto the heatmap, it is regenerated.
Value
a function that can be called
Examples
Heavy.function <- function(data) rnorm(5,mean=data)
f1=Defer(Heavy.function)
f2=function(d) Heavy.function(d)
f2(4)
f2(4) # these are not equal, as rnorm is called twice
f1(4)
f1(4) # these are equal, as the result of rnorm is cached