We could do this with cell_spec
- 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 ==
- 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

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

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))