sbac
sbac

Reputation: 2081

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(.)
```

Upvotes: 1

Views: 3983

Answers (2)

Eric
Eric

Reputation: 2849

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

Upvotes: 2

LMc
LMc

Reputation: 18642

Try

df %>%
  kable(digits = 3)

Also _if, _all, etc. verb have been superseded in dplyr >= 1.0.0 by across.

Upvotes: 4

Related Questions