Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define options programmatically

Tags:

r

I am trying to define options programmatically by using a string vector as shown below. However, the option does not get defined and it returns a NULL value. Are there any best practices or functions for this?

f <- "z" 
options(f = TRUE)
getOption("z")
# returns NULL
like image 372
Josep Espasa Avatar asked Dec 05 '25 04:12

Josep Espasa


1 Answers

According to the docs:

Options can also be passed by giving a single unnamed argument which is a named list

So you can do

f <- list(z = TRUE)
options(f)
getOption("z")
#> [1] TRUE

Or, if you want to be able to use the input format in your question, you can use the following function:

prog_options <- function(...)
{
  mc <- as.list(match.call()[-1])
  names(mc) <- 
    sapply(names(mc), function(x) eval(as.name(x), envir = parent.frame()))
  options(mc)
}

Which allows the following:

f <- "z"
g <- "y"

prog_options(f = TRUE, g = "Yes")

getOption("z")
#> [1] TRUE

getOption("y")
#> [1] "Yes"
like image 149
Allan Cameron Avatar answered Dec 07 '25 18:12

Allan Cameron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!