Search code examples
r

How to set R to default options?


I always start my scripts with:

rm(list=ls())

to clear my workspace to avoid conflicts between different scripts. However, I'm looking for a way to also set all changed options to their default state. For instance, in some scripts I need to change the SS type by setting:

options(contrasts=c(unordered="contr.sum", ordered="contr.poly"))

In other scripts I need to use the default option (and since it is default I do not specify it directly) that is:

options(contrasts=c(unordered="contr.treatment", ordered="contr.poly"))

but if a script with the changed options was just used before, the option is obviously changed without me noticing it.

Is there a command that I could put on top of my scripts to reset R to default options?


Solution

  • Like @chl said, you can save your default options somewhere, e.g. in an Rdata file using save:

    default_options = options()
    save(default_options, file = "default_options.rda")
    

    Now you can load those defaults from the file and apply them:

    load("default_options.rda")
    options(default_options)
    

    However, I would advice against running R scripts serially. In stead, if you have shared functionality between scripts, simply create functions that capture that functionality. The script you work in is then always self-contained, no influence from other, previously run scripts. Any options you set are then local to that script, and there is no need to empty your workspace or set your options to default.

    Note that I also never save my working environment, I always reconstruct my environment using the raw data and scripts that transform that raw data. If there are parts that take a lot of time, I put them in a separate script which at the end save an Rdata file using save. I then load them in the main script using load.