Mike Wise Mike Wise - 4 months ago 45
HTML Question

R knitr - kable table html formatting for small text

I am trying to format a table in R markdown (compiling to HTML) using

knitr::kable
to be as small as possible. Perhaps by making the text smaller for example. However by googling around a lot I have figured out how to control these individual elements, but the table stays the same size. I thought it should get smaller as the elements required less space, but that did not happen.

So what else do I have to set to make the table smaller?

Here is the code:

---
title: "kable table formating"
output: html_document
---
<STYLE TYPE="text/css">
<!--
td{
font-family: Arial;
font-size: 4pt;
padding:0px;
cellpadding="0";
cellspacing="0"
}
th {
font-family: Arial;
font-size: 4pt;
height: 20px;
font-weight: bold;
text-align: right;
background-color: #ccccff;
}
table {
border-spacing: 0px;
border-collapse: collapse;
}
--->
</STYLE>

```{r echo=T}
library(knitr,quietly=T)

n <- 14
m <- runif(n*n)
dim(m) = c(n,n)
df <- data.frame(m)
kable(df,padding=0)
```


And here is the output - obviously I don't need all that whitespace:

enter image description here

Answer

You only need to add format="html" to your kable call and you'll have it. By default, kable produces code for a markdown table (compare the results of kable(df) and kable(df, format = "html")

```{r echo=T}
library(knitr,quietly=T)

n <- 14
m <- runif(n*n)
dim(m) = c(n,n)
df <- data.frame(m)
kable(df, format = "html", pad=0)
```

Which looks like this:

enter image description here