[R] How to use result of approxfun in a package?

Uwe Ligges ligges at statistik.uni-dortmund.de
Fri Mar 16 11:26:23 CET 2007


* Steve Buyske <buyske at stat.rutgers.edu> [070315 19:05]:
> I am working on a project where we start with start with 2 long,  
> equal-length vectors, massage them in various ways, and end up with a  
> function mapping one interval to another. I'll call that function  
> "f1." The last step in R is to generate f1 as the value of the  
> approxfun function. I would like to put f1 into a package, but  
> without having the package redo the creation of function f1. The  
> value of approxfun is a function; for example, I have
> 
>  > f1
> function (v)
> .C("R_approx", as.double(x), as.double(y), as.integer(n), xout =  
> as.double(v),
>      as.integer(length(v)), as.integer(method), as.double(yleft),
>      as.double(yright), as.double(f), NAOK = TRUE, PACKAGE = "base") 
> $xout
> <environment: 0x17719324>
> 
> I don't really understand how this is stored, and in particular, how  
> I should handle it so as to include the function f1 in a package. I  
> would like the users to be able to load the package and use f1  
> directly, rather than re-generate it using approxfun.


approxfun() makes use of some feature of some nice lexical scoping feature:
If a function (approxfun) returns some other function (f1), then this one is stored together with the environment of the first function (approxfun).
f1 requires not only v (its formal argument), but also objects x, y, n, method, yleft, yright, and f. All these are in the envionment that was created 
at runtime of approxfun() which is referenced as <environment: 0x17719324> in your special case. 

You can save() the object f1 together with the environment as in:
    save(f1, "f1.Rdata")

and reload it later with 
    load("f1.Rdata")

In a package, this means you can either save it as data or you can specify 
the call to approxfun() directly in an R file that executes it during 
either loading the installed package or during installation if a saved 
image of the packages is used, depending on the setting in your 
DESCRIPTION file.

Uwe Ligges



 
> Thanks,
> Steve
> ---
> Steve Buyske (rhymes with "nice key")
> Associate Research Professor
> Department of Statistics & Biostatistics
> Rutgers University
> Hill Center, 110 Frelinghuysen Rd
> Piscataway, NJ 08854
> buyske at stat.rutgers.edu
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list