[R] Managing global/local variables when creating R packages
Prof Brian Ripley
ripley at stats.ox.ac.uk
Fri Aug 3 07:48:20 CEST 2007
On Thu, 2 Aug 2007, Bethany Kok wrote:
> I'm working on a package for R to create graphs for modeling
> interactions between latent variables in SEM. At the moment, I have one
> function which performs the necessary steps to prepare the data for
> graphing, and then separate graphing functions depending on what graph
> type (or types) the user wants. To get the prepped data from the setup
> function to the graphing functions, I currently put the data into a
> dataframe and declare it as a global variable (<<-). Is there a way to
> make a data frame or a set of variables available to all the functions
> in a package but NOT to users? As it is, if users were to use the var
> name of the data frame for something else, the data will be lost and
> they'll have to rerun setup before creating their graphs.
You can do this via namespaces (if an object of that name exists in the
namespace, <<- will update the object in the namespace, and functions in
the package will look first in the namespace).
However, this stateful behaviour goes against the philosophy of functional
languages, and the normal way to do this is for the setup function to
return a classed object containing the 'prepped data' which is then passed
to the graphing functions. Users familiar with R will find such a design
much easier to work with. (Those familiar with certain other statistical
packages may not.)
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-help
mailing list