Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R notebook: opts_chunk has no effect

I'm working on my first R notebook which works pretty well, except for one issue. I'd like to be the numbers that I output inline with

`r realbignumber`

to have commas as separator and max 2 decimal points: 123,456,789.12

In order to achieve this, I added a chunk at the beginning of my document, which contains...

```{r setup}
knitr::opts_chunk$set(echo = FALSE, warning=FALSE, cache = TRUE, message = FALSE)
knitr::opts_chunk$set(inline = function(x){if(!is.numeric(x)){x}else{prettyNum(round(x,1), big.mark = ",")}})
options(scipen=999)
```

The suppression of scientific numbers works like a charm, so the chunk is definitely executed. However, formatting of the inline output of numbers does not work.

Any ideas why that could be? Do these kinds of settings generally not work with R notebooks?

Edit:

The solution suggested here also has no effect on the output format of numbers.

like image 425
Me Myself Avatar asked Dec 16 '16 14:12

Me Myself


1 Answers

Here is an example illustrating two ways to print a large number in an R Markdown document. First, code to use the prettyNum() function in an inline R chunk.

Sample document where we test printing a large number. First set the number in an R chunk. 
```{r initializeData}
theNum <- 1234567891011.03
options(scipen=999,digits=16)
```

The R code we'll use to format the number is: `prettyNum(theNum,width=23,big.mark=",")`.

Next, print the large number. `r prettyNum(theNum,width=23,big.mark=",")`.

The alternative of using chunk options works as follows.

 Now, try an alternative using knitr chunks.

 ```{r prettyNumHook }
 knitr::knit_hooks$set(inline = function(x) { if(!is.numeric(x)){ x }else{ prettyNum(x, big.mark=",",width=23) } })
 ```
 Next, print the large number by simply referencing the number in an inline chunk as `theNum`: `r theNum`. 

When both chunks of code are embedded in an Rmd file and knit, the output is as follows, showing that both techniques produce the same result.

enter image description here

regards,

Len

like image 146
Len Greski Avatar answered Oct 14 '22 12:10

Len Greski