Skip to contents

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 + to the result of the deferred function

cache

use caching mechanism

width.height

a vector containing the desired width and height (not checked!)

Value

a function that can be called

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.

Examples

Heavy.function <- function(data) rnorm(5,mean=data)
f1=Defer(Heavy.function)
f2=function(d) Heavy.function(d)
f2(4)
#> [1] 3.881671 4.230242 4.100830 3.913772 2.556357
f2(4) # these are not equal, as rnorm is called twice
#> [1] 3.537206 4.417075 3.285470 4.569574 4.208648
f1(4)
#> [1] 4.276099 4.137438 5.083157 4.367007 2.334104
f1(4) # these are equal, as the result of rnorm is cached
#> [1] 4.276099 4.137438 5.083157 4.367007 2.334104