[R] Help with saving user defined functions

George Trojan - NOAA Federal george.trojan at noaa.gov
Sun Feb 12 23:11:08 CET 2017


I can't figure out how to save functions to RDS file. Here is an example
what I am trying to achieve:

> t <- rnorm(100)
> cdf <- ecdf(t)
> cdf(0)
[1] 0.59
> saveRDS(cdf, "/tmp/foo")
>
Save workspace image? [y/n/c]: n
[gtrojan at asok petproject]$ R
> cdf <- readRDS("/tmp/foo")
> cdf
Empirical CDF
Call: ecdf(t)
x[1:100] = -2.8881, -2.2054, -2.0026,  ..., 2.0367, 2.0414

This works. However when instead of saving cdf() I try to save function

> trans <- function(x) qnorm(cdf(x) * 0.99)

after restoring object from file I get an error:

> trans <- readRDS("/tmp/foo")
> trans(0)
Error in qnorm(cdf(x) * 0.99) : could not find function "cdf"

I tried to define and call cdf within the definition of trans, without
success:

> tmp <- rnorm(100)
> trans <- function(x) { cdf <- ecdf(tmp); cdf(0); qnorm(cdf(x)) * 0.99 }
> saveRDS(trans, "/tmp/foo")
Save workspace image? [y/n/c]: n

> trans <- readRDS("/tmp/foo")
> trans
function(x) { cdf <- ecdf(tmp); cdf(0); qnorm(cdf(x)) * 0.99 }
> trans(0)
Error in sort(x) : object 'tmp' not found

So, here the call cdf(0) did not force evaluation of my random sample. What
am I missing?

George

	[[alternative HTML version deleted]]



More information about the R-help mailing list