[R] Define package-wide character constants

Duncan Murdoch murdoch.duncan at gmail.com
Tue Jul 13 14:25:36 CEST 2010


On 13/07/2010 8:20 AM, Daniel Nüst wrote:
> Dear list!
>
> I develop a package for R and wonder how I can best define
> package-wide constants (both character strings or named vectors of
> strings) which are used throughout different classes and methods. I'm
> new to R and wonder if there is some kind of “best practice” that I
> just haven't read of yet. My main programming language is Java, so if
> that helps anyone to understand my thinking: I mean values that I
> would normally put into a class like Constants.java as “public static
> final” variables, or into a .properties file.
>
> A concrete example: I deal with XML files, both parsing and encoding.
> Right now I have several classes representing documents which I
> handle, and in each of the encoding methods there is a character
> string for the schema location. If I want to change that location then
> I have to change it several times (neglecting search and replace), but
> I'd rather have a single point of change for that.
>
> I've read documentation on environments, "<<-" and the "assign"
> function, BUT am still not sure how to approach my problem BEST.
> "assign" could most probably do the job, but do I use/create a certain
> environment (like "myConstants")? Or should I just use my package's
> environment?
>
>
> Thanks for any experiences, (alternative) ideas, or pointers at
> existing discussions!

If they are constants, you won't need to use <<- or assign() to change 
them:  just define them at top level in one of the source files for your 
package.
For example,

errorMsg <- "You have made an error."

Then you can refer to them in functions in your package, e.g.

foo <- function() {
  stop(errorMsg)
}

If you use a NAMESPACE file you can limit the visibility of these 
objects to your package by not exporting them.

Duncan Murdoch



More information about the R-help mailing list