Search code examples
r-markdownunits-of-measurementbookdownkable

Get a second header with the units of columns


Sometimes in academic texts one wants to present a Table in which every column has units. It is usual that the units are specified below the column names, like this

|Object       |Volume  |   area  | Price    | 
|             |$cm^3$  |$cm^2$   |   euros  |
|:------------|:-------|--------:|---------:|
|A            |3       |    43.36|    567.40|
|B            |15      |    43.47|   1000.80|
|C            |1       |    42.18|      8.81|
|D            |7       |    37.92|      4.72|

How could I achieve this for my bookdown documents?

Thank you in advance.


Solution

  • Here is a way using kableExtra:

    ```{r}
    library(kableExtra)
    df <- data.frame(Object = LETTERS[1:5], 
                     Volume = round(runif(5, 1, 20)),
                     area   = rnorm(5, 40, 3),
                     Price  = rnorm(5, 700, 200))
    
    colNames <- names(df)
    dfUnits <- c("", "$cm^3$",  "$cm^2$", "€")
    
    kable(df, col.names = dfUnits,escape = F, align = "c") %>%
      add_header_above(header = colNames, line = F, align = "c")
    ```
    

    enter image description here