bold entries in r data.frame RMarkdown

Viewed 198

I am listing my results in RMarkdown. I want to show max values in each column in bold. How can I do that? See the code, and output (as png) below please.

data<-data.frame(A=c(1,2,4,3),  B=c(8,7,9,10), C=c(14,12,13,11), D=c(15,18,17,16))
rownames(data)<-c("E", "F", "G", "H")

library(knitr)
library(kableExtra)

kable(data) %>%
  kable_styling(
    full_width = FALSE,
    bootstrap_options = c("striped", "hover", "condensed"), 
  ) %>%
  add_header_above(c( '', Group1 = 2, Group2 = 2))

enter image description here

1 Answers

We could do this with cell_spec

  1. Loop across the columns of the dataset, add the cell_spec layer with bold argument as a logical vector i.e. TRUE where the column value is max with ==
  2. Convert to kable and use the OP's code as in the post
library(dplyr)
library(knitr)
library(kableExtra)
data %>%
  mutate(across(everything(), ~ cell_spec(., bold = . == max(.)))) %>%
  kable(escape = FALSE, booktabs = TRUE) %>%
  
  kable_styling(
    full_width = FALSE,
    bootstrap_options = c("striped", "hover", "condensed"), 
  ) %>%
  add_header_above(c( '', Group1 = 2, Group2 = 2)) 

-output

enter image description here


If this needs to be by row maxs, then an option would be to transpose

data %>% t %>%
  as.data.frame %>%
  mutate(across(everything(), ~ cell_spec(., bold = . == max(.)))) %>%
  t %>%
  as.data.frame %>%
  kable(escape = FALSE, booktabs = TRUE) %>%
  
  kable_styling(
    full_width = FALSE,
    bootstrap_options = c("striped", "hover", "condensed"), 
  ) %>%
  add_header_above(c( '', Group1 = 2, Group2 = 2)) 

-output

enter image description here


Or for the rowwise, create the cell_spec layer with apply

data[] <- t(apply(data, 1, function(x) cell_spec(x, bold = x == max(x))))

data %>%
  kable(escape = FALSE, booktabs = TRUE) %>%
  
  kable_styling(
    full_width = FALSE,
    bootstrap_options = c("striped", "hover", "condensed"), 
  ) %>%
  add_header_above(c( '', Group1 = 2, Group2 = 2)) 

Or may use dapply from collapse for faster execution

library(collapse)
dapply(data, MARGIN = 1, FUN = function(x) cell_spec(x, bold = x == fmax(x))) %>% 
  kable(escape = FALSE, booktabs = TRUE) %>%
  
  kable_styling(
    full_width = FALSE,
    bootstrap_options = c("striped", "hover", "condensed"), 
  ) %>%
  add_header_above(c( '', Group1 = 2, Group2 = 2)) 
Related