How to format all numbers in a table in r using kable?
Asked Answered
C

1

13

Code output

I need to be able to reduce or simplify the numbers in this table. I want only up to 4 decimal places shown and if possible only integers if the number is a whole number. How would I accomplish this?

library(kableExtra)
x = c(1, 1, 1, 1, 1, 1, 1, 1, 1)
y = x/2
z = x/3
a = data.frame(x, y, z)
b = t(a)
c = kable(b, "html", align = "c") %>%
  kable_styling(full_width = F)
Convocation answered 10/3, 2019 at 22:48 Comment(1)
@eipi10 - the digits argument by itself is insufficient to print x with no decimals.Irtysh
I
11

Use the format() function to convert the data to the minimum number of decimals needed to render the data. Using the code from the original post:

library(knitr)
library(kableExtra)
x = c(1, 1, 1, 1, 1, 1, 1, 1, 1)
y = x/2
z = x/3

a = data.frame(x = format(x,digits=4,nsmall = 0), 
               y = format(y,digits=4,nsmall = 0), 
               z = format(z,digits = 4,nsmall = 0))
b = t(a)
c = kable(b, "html", align = "c") %>%
  kable_styling(full_width = F)

...and the output:

enter image description here

Incorporating Martin Schmelzer's comments, a tidyverse version of the same solution looks like this.

# tidyverse alternative
library(knitr)
library(kableExtra)
library(dplyr)
x = c(1, 1, 1, 1, 1, 1, 1, 1, 1)
y = x/2
z = x/3
data.frame(x,y,z) %>% 
   mutate_if(is.numeric, format, digits=4,nsmall = 0) %>% t(.) %>% kable(.,"html",align = "c") %>% 
   kable_styling(full_width = F) -> c
Irtysh answered 11/3, 2019 at 0:49 Comment(3)
df %>% mutate_if(is.numeric, format, digits=4) %>% kable makes life easier.Acquaint
@MartinSchmelzer - your code is missing the nsmall argument and the t(.) function in the pipeline, but I incorporated those items and added the tidyverse version to the answer. Thanks for the feedback!Irtysh
Well aware of what was missing. Since I only commented without any output I saw no need for that since the focus was on conditional mutation.Acquaint

© 2022 - 2024 — McMap. All rights reserved.