The options mechanism in R

02 Mar 2013
2013/03/02

Customization in R.

Basics

Several features benefit from being customizable — either because of personal taste or specifics of the environment.

The way R implements this flexibility is through the options function.  This both sets and reports options.  For example, we can see the names of the options that are set by default:

> names(options())
 [1] "add.smooth"            "browser"              
 [3] "browserNLdisabled"     "check.bounds"         
 [5] "continue"              "contrasts"            
 [7] "defaultPackages"       "demo.ask"             
 [9] "device"                "device.ask.default"   
[11] "digits"                "echo"                 
[13] "editor"                "encoding"             
[15] "example.ask"           "expressions"          
[17] "help.search.types"     "help.try.all.packages"
[19] "help_type"             "HTTPUserAgent"        
[21] "internet.info"         "keep.source"          
[23] "keep.source.pkgs"      "locatorBell"          
[25] "mailer"                "max.print"            
[27] "menu.graphics"         "na.action"            
[29] "nwarnings"             "OutDec"               
[31] "pager"                 "papersize"            
[33] "pdfviewer"             "pkgType"              
[35] "prompt"                "repos"                
[37] "scipen"                "show.coef.Pvalues"    
[39] "show.error.messages"   "show.signif.stars"    
[41] "str"                   "str.dendrogram.last"  
[43] "stringsAsFactors"      "timeout"              
[45] "ts.eps"                "ts.S.compat"          
[47] "unzip"                 "useFancyQuotes"       
[49] "verbose"               "warn"                 
[51] "warning.length"        "width"                
[53] "windowsTimeouts"

options returns a list.  Most of the options are not especially interesting — we’ll highlight a few of the most useful.

digits

The digits option controls how many digits are printed (by default):

> 100/998
[1] 0.1002004
> options("digits")
$digits
[1] 7

The default value is 7.  We can change it:

> options(digits=4, prompt="R> ")
R> 100/998
[1] 0.1002
R> getOption("digits")
[1] 4
R> options(digits=20)
R> 100/998
[1] 0.10020040080160320939

Notice that the last few digits are noise (as per Circle 1 of The R Inferno).

A sort of related option is scipen — this controls which numbers are printed in scientific notation.

width

The width option says how many characters R should put on a line.  Adjusting this can be useful, for instance, if you write a blog and paste code into a place that doesn’t want many characters on a line.

If you get responses from R that look messy, it could be that width is larger than it should be.

warn

If you experience R trauma, the warn option can be useful.  This takes the values:

  • 0: (the default) warnings are saved up until the top-level prompt is returned
  • 1: warnings are issued as soon as possible
  • 2: warnings are converted into errors (useful in combination with the error option)
  • -1(actually any negative number): do not issue warnings

error

This was not in the list above because its default value is NULL.  That is the wrong value for almost all people almost all of the time.  There are (at least) two better values.

The first better value is dump.frames:

R> options(error=dump.frames)
R> stop("here is an error")
Error: here is an error
R> debugger()
Message:  Error: here is an error
Available environments had calls:
1: stop("here is an error")

Enter an environment number, or 0 to exit  
Selection:

The second better value is recover:

R> options(error=recover)
R> stop("here is a second errrrror")
Error: here is a second errrrror
No suitable frames for recover()

The (important) difference is that with recover you are thrown into the debugger automatically (if possible) when you encounter an error.  In contrast you need to call debugger yourself if you use dump.frames.

Of course in the examples here there is nothing to debug, but if this were a real emergency, then you would be presented with a stack of frames any of which you could enter and explore.

If you want to automatically change this option at startup, then you’ll want to specify the namespace (because not everything will be in place):

R> options(error=utils::dump.frames)
R> options(error=utils::recover)

safety

If you intend to change an option but misspell it, then you have added a new option instead of changing the old one.  Page 45 of S Poetry has a function that warns you if you are adding any options.  That function would almost work in R except withVisible would be used instead of .Auto.print.

Programming

You are not restricted to the existing options.  You can use a new option of your choosing.  Options are usually not necessary for things that only impact one function — an argument with a default suffices in that setting.

Suppose we want to use a new option called leave.  This will obviously not be set in most people’s options.  A typical idiom is:

leave <- getOption("leave")
if(is.null(leave)) leave <- "drop off key"

In most cases the test should be more strict than just testing for NULL.

Deep End

In an R-devel thread started by Charles Geyer, Thomas Lumley offered the following function:

withOptions <- function(optlist, expr)
{
  oldopt <- options(optlist)
  on.exit(options(oldopt))
  expr <- substitute(expr)
  eval.parent(expr)
}

This is an easy way to temporarily change one or more options while an expression is evaluated.

It is used like:

 R> print((1:10)^-1)
 [1] 1.0000000 0.5000000 0.3333333 0.2500000 0.2000000
 [6] 0.1666667 0.1428571 0.1250000 0.1111111 0.1000000
 R> withOptions(list(digits=3), print((1:10)^-1))
 [1] 1.000 0.500 0.333 0.250 0.200 0.167 0.143 0.125
 [9] 0.111 0.100

Extra credit for understanding:

 R> withOptions(list(digits=3), (1:10)^-1)
 [1] 1.0000000 0.5000000 0.3333333 0.2500000 0.2000000
 [6] 0.1666667 0.1428571 0.1250000 0.1111111 0.1000000

Epilogue

Make a new plan, Stan

from “50 Ways to Leave Your Lover” by Paul Simon

Previously

Other R language posts are:

Tags:
4 replies
  1. Liviu says:

    “A sort of related option is scipen — this controls which numbers are printed in scientific notation.”

    Patrick,
    Would you mind to elaborate on scipen? This is part of my R childhood traumas, especially when printing an lm summary with a lot of figures in scientific notation. And I still don’t quite understand the option.

    Thanks!

    Reply
  2. Patrick Burns says:

    Liviu,
    I’m reasonably sure that I can’t give you rationality. The idea is that scipen is a penalty regarding how much space is used with and without scientific notation. Here is an example that might help:

    > options(scipen=0)
    > print(c(3e4, 3e-2))
    [1] 3e+04 3e-02
    > print(c(3e4, 3e-1))
    [1] 3e+04 3e-01
    > print(c(3e4, 3e0))
    [1] 30000 3
    > print(c(3e4, 3e1))
    [1] 30000 30
    >
    > options(scipen=1)
    > print(c(3e4, 3e-2))
    [1] 3e+04 3e-02
    > print(c(3e4, 3e-1))
    [1] 3e+04 3e-01
    > print(c(3e4, 3e0))
    [1] 30000 3
    > print(c(3e4, 3e1))
    [1] 30000 30
    >
    > options(scipen=2)
    > print(c(3e4, 3e-2))
    [1] 3e+04 3e-02
    > print(c(3e4, 3e-1))
    [1] 30000.0 0.3
    > print(c(3e4, 3e0))
    [1] 30000 3
    > print(c(3e4, 3e1))
    [1] 30000 30
    >
    > options(scipen=-1)
    > print(c(3e4, 3e-2))
    [1] 3e+04 3e-02
    > print(c(3e4, 3e-1))
    [1] 3e+04 3e-01
    > print(c(3e4, 3e0))
    [1] 3e+04 3e+00
    > print(c(3e4, 3e1))
    [1] 3e+04 3e+01

    Reply
  3. Liviu says:

    Patrick,
    Thanks for the examples. I don’t see much rationality, but the examples help.

    Reply

Trackbacks & Pingbacks

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© Copyright - Burns Statistics