[This article was first published on My Experiments with R » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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.

<<echo = F>>=
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, echo = T>>=
format_all = function(...){

library(plyr)
# 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))
rm(tmp);

}
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  