Search code examples
rvariadic-functionsgetter-settersettervariadic

How to develop a function called `setOption`?


R::base has a function called getOption that works as expected.

getOption("max.print");

I can't find the inverse function setOption. Please let me know where it is?

If it doesn't exist, can we write one?

setOption("max.print", 20);

where the function is in skeleton form:

setOption = function(myKey, myValue)
    {
    
    
    }

I tried the obvious:

options()[["max.print"]] = 20

which throws an error.

Maybe something with:

onames = names(options());
options(setNames( ???

The above code is unfinished, hence this question.

Here is an example of a variadic getter-setter function for the "par":

setParKey = function(myKey, myValue)
    {
    pnames = names( par(no.readonly = TRUE) );
    if(is.element(myKey, pnames))
        {
        par(setNames(list(myValue), myKey))
        }
    }

Solution

  • setOption <- options
    setOption(max.print = 20)
    getOption("max.print")
    #> [1] 20
    

    or closer to your interface (using R package rlang):

    setOption <- function(myKey, myValue) rlang::exec('options', !!myKey := myValue)
    setOption('max.print', 30)
    getOption("max.print")
    #> [1] 30
    

    I am not sure I understand your point about variadic functions, but the function options() is already variadic...

    setOptions <- options
    setOptions(max.print = 20, digits = 12)
    getOption("max.print")
    #> [1] 20
    getOption("digits")
    #> [1] 12