I have a function which requires that I set an option, namely stringsAsFactors=FALSE
. My all-too common approach was to store the existing value at the onset of the function
op <- option("stringsAsFactors")
and before calling return(x)
make sure to call
options(op)
While that works, it's a lengthy and complex function that can return from several places, so I need to either make sure every return(x)
is preceded by options(op)
, or create a tiny function (itself inside my function) that does only that:
returnfunc <- function(x) {
options(op)
return(x)
}
So my question is: what would be a better way to do that? Specefically, one that would prevent that the function exits with an error and leave the parameter (unduly) modified?
You could also add a default argument that allows the user to change it if they wish, and then pass the argument into the function that uses it.
For example,
This way, you can change it to
TRUE
if you want, and nooptions()
are changed. You really don't want to be messing around withoptions()
inside of functions.There's a built in
on.exit
function that does exactly this. For exampleYou can change what ever options you want in the
options()
call and it returns all the values before the changes as list so it's easy to reset. You can pass whatever expression you want toon.exit
, here we just set the options back to what they were. This will run when ever the function exits. See?on.exit
for more info.