R using temporary parameter settings inside a function
I have a function that requires me to set a parameter, namely stringsAsFactors=FALSE
. My all too general approach was to keep the existing value at the beginning of the function
op <- option("stringsAsFactors")
and before calling return(x)
be sure to call
options(op)
While this works, it is a long and complex function that can return from multiple places, so I need to either make sure each is return(x)
preceded options(op)
, or create a tiny function (itself inside my function) that does just that:
returnfunc <- function(x) {
options(op)
return(x)
}
So my question is, what would be the best way to do this? Specifically, would one of them prevent the function from exiting with an error and leave the parameter (unnecessarily) changed?
source to share
There's a built-in function on.exit
that does exactly that. for example
f<-function() {
op <- options(stringsAsFactors=FALSE)
on.exit(options(op))
read.table(...)
}
You can change whatever parameters you want in the call options()
and return all values before the changelog so that it can be easily reset. You can pass any expression you want on.exit
, here we'll just return the parameters as they were. This will run when the function exits. See ?on.exit
for more information.
source to share
You can also add a default argument which allows the user to change it if they wish, and then pass the argument to the function that uses it.
For example,
f <- function(x, stringsAsFactors = FALSE) {
read.csv(..., stringsAsFactors = stringsAsFactors)
}
This way you can change it to TRUE
if you like and not change options()
. You really don't want to mess with options()
inside functions.
source to share