Search code examples
rr-markdownkable

How to format number of digits with kable


I want to format x and y using 3 digits: e.g. for x I want to obtain 0.035, 0.790, 0.453.

I tried using the following, without success:

---
title: "format 3 digits"
output:
  word_document: default
---

```{r echo=FALSE,message=FALSE, warning=FALSE}
library(tidyverse)
library(knitr)

df <- tibble(x = c(0.0345, 0.7898, 0.4534),
             y = c(-0.0345, -0.7898, -0.4534),
             z = c(1, 2, 3))
df %>%
  mutate_if(is.numeric, format, digits=3, nsmall=0) %>%
  kable(.)
```

Solution

  • Responding to LMc's solution. Here is an option using across.

    library(tidyverse)
    library(knitr)
    
    df <- tibble(x = c(0.0345, 0.7898, 0.4534),
                 y = c(-0.0345, -0.7898, -0.4534),
                 z = c(1, 2, 3))
    df %>%
      mutate(across(where(is.numeric), ~ round(., digits = 3))) %>%
      kable(.)
    

    enter image description here