[R] Change R options only inside a package
Helios de Rosario
helios.derosario at ibv.upv.es
Mon Jul 15 11:27:38 CEST 2013
Hi,
What should I do if I want to use "non-default" R-options for the
functions inside a package, but not affect the options of the rest of
the session? Specifically, I'm thinking of using "sum contrasts" instead
of the default, in functions like "lm", etc. when they are called by
other functions in a package.
I can think on the following solutions:
1) Quick-and-dirty solution: use options() to modify the default
contrasts before calling my functions. If I don't want to affect the
rest of the session, I should reset the options before returning,
preferably with exception handling to avoid that the options are not
reset if my function fails.
2) Complex-but-tidier solution: Use function-specific arguments to tell
the contrasts of the factors that I'm using. E.g., I should create a
named list of contrasts and pass it as the argument "contrasts" every
time I call "lm":
mod <- lm(form, contrasts=list(factor1="contr.sum",
factor2="contr.sum"))
3) Encapsulated solution: create package-specific (unexported) versions
of "lm" and other functions, that already implement #2, e.g.:
lm <- function(...)
{
# Code that examines dots, to get the factors of the model, and create
the list of contrasts
# Then call the stats lm (be sure that dots did not already include a
"contrasts" element).
stats::lm(..., contrasts = list.of.factors.with.sum.contrasts)
}
I don't like #1, because changing the options back and forth may be
error-prone and lead to unexpected behaviour.
#2 is better, but prone to programmer errors: I should be careful of
not forgetting to set the "contrasts" argument every time I call "lm".
I prefer #3, because it avoids the disadvantages of the previous
solutions, but perhaps it is overkill, hence my question: Is there a
"clean" way of setting the R-session options in such a way that they
only affect the functions and data inside a package?
Thanks and best regards
Helios De Rosario
INSTITUTO DE BIOMECÁNICA DE VALENCIA
Universidad Politécnica de Valencia • Edificio 9C
Camino de Vera s/n • 46022 VALENCIA (ESPAÑA)
Tel. +34 96 387 91 60 • Fax +34 96 387 91 69
www.ibv.org
Antes de imprimir este e-mail piense bien si es necesario hacerlo.
En cumplimiento de la Ley Orgánica 15/1999 reguladora de la Protección
de Datos de Carácter Personal, le informamos de que el presente mensaje
contiene información confidencial, siendo para uso exclusivo del
destinatario arriba indicado. En caso de no ser usted el destinatario
del mismo le informamos que su recepción no le autoriza a su divulgación
o reproducción por cualquier medio, debiendo destruirlo de inmediato,
rogándole lo notifique al remitente.
More information about the R-help
mailing list