Globally Set Digits in Sweave

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

Advertisements

2 thoughts on “Globally Set Digits in Sweave

  1. baptiste

    that looks quite dangerous to me; what if you use some of the affected variables later in the Sweave document?

    Reply
    1. rstats Post author

      hmmmm. i see your point. one way to alleviate this problem is to create a copy of all the numeric variables in the environment, format them using this function and reserve their use only for \Sexpr statements. So for every variable x, there is a formatted copy x* which can be used in \Sexpr. What do you think about this solution? Any other suggestions on how to make this work without any dangerous side effects?

      Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s