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)
The kable() function in knitr is a very simple table generator, and is simple by design. It only generates tables for strictly rectangular data such as matrices and data frames. You cannot heavily format the table cells or merge cells.
Function 'kable()' is a light weight table generator coming from 'knitr'. This package simplifies the way to manipulate the HTML or 'LaTeX' codes generated by 'kable()' and allows users to construct complex tables and customize styles using a readable syntax. Version: 1.3.4.
Acronym. Definition. KABLE. Ka-Band Link Experiment.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With