[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
{"extraction_info": {"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "math_score": 0.21939370036125183, "perplexity": 1819.8786958203232}, "config": {"markdown_headings": true, "markdown_code": true, "boilerplate_config": {"ratio_threshold": 0.18, "absolute_threshold": 10, "end_threshold": 15, "enable": true}, "remove_buttons": true, "remove_image_figures": true, "remove_link_clusters": true, "table_config": {"min_rows": 2, "min_cols": 3, "format": "plain"}, "remove_chinese": true, "remove_edit_buttons": true, "extract_latex": true}, "warc_path": "s3://commoncrawl/crawl-data/CC-MAIN-2021-31/segments/1627046153899.14/warc/CC-MAIN-20210729234313-20210730024313-00027.warc.gz"}