Search code examples
rfunctionglobalenvironment

Changing options() in a function environment without changing options() in global environment in R?


To suppress exponential notation for numerics, in my global environment I have options("scipen" = 100). To do some stuff where i need exponential notation, I want to temporarily change this option inside of a function, like

f <- function(x){
                 options("scipen" = -100)
                 ...
}

However, changing the options inside a function automatically changes the options in the global environment as well. Is there a way to change options locally inside the function only?


Solution

  • This is a good place to use on.exit(). It has the virtue of ensuring that the options get reset to their original values (stored in oo) before the evaluation frame of the function call is exited -- even if that exit is the result of an error.

    f <- function(x) {
        oo <- options(scipen = -100)
        on.exit(options(oo))
        print(x)
    }
    
    ## Try it out
    1111
    ## [1] 1111
    f(1111)
    ## [1] 1.111e+03
    1111
    ## [1] 1111