Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R using temporary options settings inside a function

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?

like image 952
Dominic Comtois Avatar asked Aug 09 '14 04:08

Dominic Comtois


People also ask

How do you pass a function as a parameter in R?

Adding Arguments in R We can pass an argument to a function while calling the function by simply giving the value as an argument inside the parenthesis.

What is the options function in R?

The options() function in R is used to set and examine different global options that affects the way in which R determines and returns its results.

What is a function call in R?

call R function executes a function by its name and a list of corresponding arguments. The call The call R function creates objects of the class “call”.


2 Answers

There's a built in on.exit function that does exactly this. For example

f<-function() {
    op <- options(stringsAsFactors=FALSE)
    on.exit(options(op))

    read.table(...)
}

You 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 to on.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.

like image 73
MrFlick Avatar answered Sep 21 '22 00:09

MrFlick


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,

f <- function(x, stringsAsFactors = FALSE) {

        read.csv(..., stringsAsFactors = stringsAsFactors)

}

This way, you can change it to TRUE if you want, and no options() are changed. You really don't want to be messing around with options() inside of functions.

like image 21
Rich Scriven Avatar answered Sep 19 '22 00:09

Rich Scriven