Search code examples
rr-markdownkableextra

kableExtra : How can i set to bold the biggest value of the row?


Suppose i have a table that looks like :

x = matrix(runif(10*5),nrow=10,ncol=5)

When i display the matrix using kableextra, i want the highest value, per row, of say the last 2 rows, to be bolded.

I looked at this document https://rdrr.io/cran/kableExtra/f/inst/doc/awesome_table_in_pdf.pdf a lot and i did not found how to use cell_spec correctly to perform this goal.


Solution

  • I thought this would be easier than it turned out to be. As far as I can see, this is how to do it:

    ---
    title: "Untitled"
    output:  pdf_document
    ---
    
    ```{r}
    set.seed(123)
    library(knitr)
    library(kableExtra)
    x <- matrix(round(runif(10*5),2), nrow=10,ncol=5)
    j1 <- which.max(x[9,])
    j2 <- which.max(x[10,])
    col <- seq_len(ncol(x))
    x[9,] <- x[9,] %>% cell_spec(bold = col == j1)
    x[10,] <- x[10,] %>% cell_spec(bold = col == j2)
    x %>% kable(booktabs = TRUE, escape = FALSE)
    ```
    

    A few notes:

    • I rounded the values so they aren't so ugly when printed.
    • I couldn't see a way to do everything in one pipeline, though there probably is one. The trouble is that cell_spec is designed to work on vectors, not matrices.
    • Finally, the escape = FALSE in kable() is essential: otherwise you'll see the code to make it bold, rather than the bold entry itself.