Search code examples
pdfr-markdownknitrkableextra

Selecting and colouring single table cells with kableExtra in R markdown cell_spec


I use R markdown in combination with LaTeX to create dynamic PDF reports. To generate the summarizing tables I use the kableExtra package.

I'd like to change the styling of individual cells.

Example: Consider the R dataframe mtcars[1:10, 1:5]. Using this would be rendered into some nice table:

kable(mtcars[1:10, 1:5], format="latex", booktabs = T)` 

Rendered table

Now I want to change the style of certain cells. Say the 2nd and 8th entry of mpg should be green, the 4th and 5th of disp should be orange and italicized and the last four entries of drat should be red and bold. And the same cells should be like that, no matter which entries are in the cells.

I'm perfectly aware of the documentation and the examples, such as row and column specific colouring. But the documentation for cell_spec deals only with conditional logic depending on the cell values, while I'd like to colour the cells independently.


Solution

  • As you have seen, the cell_spec function is useful if you want to colour a whole row or column. As kableExtra does not supply a function to directly edit a single cell, the "easiest" way to do this is to directly paste the LaTeX commands into the cell. I have used this approach in a similar answer here:

    ---
    output: pdf_document
    header-includes:
      - \usepackage{booktabs}
    ---
    
    ```{r pressure, echo=FALSE}
    
    df <- mtcars[1:10, 1:5]
    
    df[1,5] <- paste0("\\underline{", df[1,5], "}")
    df[1,1] <- paste0("\\textcolor{red}{", df[1,1], "}")
    df[2,2] <- paste0("\\textcolor{green}{\\textbf{", df[2,2], "}}")
    # # Equivalent to:
    # library(kableExtra)
    # df[1, 5] <- cell_spec(df[1, 5], "latex", underline = T)
    # df[1, 1] <- cell_spec(df[1, 1], "latex", color = "red")
    # df[2, 2] <- cell_spec(df[2, 2], "latex", color = "green", bold = T)
    
    knitr::kable(df, format="latex", booktabs = T, escape = F)
    
    ```
    

    enter image description here

    You can adapt this to work for your example. You may want to check out the available LaTeX formatting here: https://www.sharelatex.com/learn/Bold,_italics_and_underlining