R knitr - kable table html formatting for small text

12,036

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 gives you this:

enter image description here

Share:
12,036
Mike Wise
Author by

Mike Wise

Long time programmer, prefer numerical or graphics programming. Current languages are C#, Python, R, PowerShell, in that order. Past languages (that I was once good at but have not used in several to very many years) are Perl, C++, C, Pascal, Prolog, Fortran (and of course Assembler...). OpenGL and PHIGS (anyone remember that?) are also obsessions from my past.

Updated on July 25, 2022

Comments

  • Mike Wise
    Mike Wise almost 2 years

    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

  • Mike Wise
    Mike Wise over 8 years
    Yep, that did it. Thanks a lot, don't see how I would have found that.
  • Mike Wise
    Mike Wise almost 6 years
    Added a display of the results so you can see how much better it is.