Globally Set Digits in Sweave

March 30, 2011

(This article was first published on My Experiments with R » R, and kindly contributed to R-bloggers)

I use Sweave regularly for most of my writing and love the way it works. However, one issue that often irks me is the inability to globally set the number of digits to display. Here is a minimal example that illustrates my point.

options(digits = 2);
x = 1.2345;
y = 1.214432532;
z = 124.23414513;

If we now display the numbers using Sexpr, this is what we get

x = 1.2345
y = 1.214432532
z = 124.23414513

Note how setting the number of digits to display using options did not have any impact. The reason for this is that Sexpr treats every variable as a character and hence the digits option does not work.

A simple solution to rectify this issue is to use functions like format or round to preset the number of digits inside the sweave chunk. However, this approach requires one to apply these functions on every variable individually, which in my opinion leads to some ugly code within the chunks.

This set me thinking whether it was possuble to write a function that (a) selects all the numeric variables created inside a chunk, and (b) formats them using global options. It turns out that it is possible to do this and in fact is quite straightforward.

format_all = function(...){
  # get all numeric variables
  num.obj = ls.str(mode = 'numeric', envir = .GlobalEnv);

  # apply format to all numeric variables
  l_ply(num.obj, function(.x) 
    assign(.x, as.numeric(format(get(.x), ...)), envir = .GlobalEnv))
format_all(digits = 3, nsmall = 2);

If we now display the numbers using Sexpr, this is what we get

x = 1.23
y = 1.21
z = 124.23

To leave a comment for the author, please follow the link and comment on their blog: My Experiments with R » R. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)