How to set a decimal display pattern in R?

Asked

Viewed 620 times

5

I have a rmarkdown script that generates a report in . pdf.

I would like to standardize the number of decimal places displayed, without needing to round() in every function.

At the beginning of the script, I tried to use:

options(scipen=30, digits=3)

This prevents the values from appearing as scientific notation, but the number of decimals is still varying. It is possible to create this pattern?

  • 1

    I know with format(X, nsmall=3) it will show numbers like 1 and 1.5 as 1,000 and 1,500, but I don’t know of a global option for this.

  • 1

    options(digits) is considered a "suggestion"; any function that specifies the number of boxes to display some result will have provenance. If you are generating the documents via Pandoc, take a look at the function pander::panderOptions.

  • @Carloseduardolalike thanks! interesting this library Pander! Will help a lot!

1 answer

4


It is possible to accomplish this for the Chunk and to inline.

See in the example below: the real value, value with modification for inline and the modification to the Chunk.

inserir a descrição da imagem aqui

The code below is in rmd, and consists of head, print original values (Chunk 1), function for adjustment inline (Chunk 2), adjustment to print as a result (Chunk 3) and print values default to decimal places (Chunk 4).

---
title: "Untitled"
output: html_document
---
## R Markdown
```{r }
mean(mtcars$mpg)
pi
```
\
Valor de pi é igual a `r pi`.
\

## MOD - INLINE
```{r  , include=FALSE}
library(knitr)
inline_hook <- function (x) {
  if (is.numeric(x)) {
    res <- ifelse(x == round(x),
      sprintf("%d", x),
      sprintf("%.3f", x) # numero de casas decimais
    )
    paste(res, collapse = ", ")
  }
}
knit_hooks$set(inline = inline_hook)
```
\
Valor de pi é igual a `r pi`.
\

## MOD - CHUNK
```{r  , include=FALSE}
options(digits = 4)
```

```{r }
mean(mtcars$mpg)
pi
```

Source: inline.

  • 1

    Very interesting these functions! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.