Home > Software engineering >  How to make cells bold in KableExtra based on a condition
How to make cells bold in KableExtra based on a condition

Time:10-27

My data looks like this as a kable:

pdtable %>%
  kbl(caption = "This is the caption") %>%
  kable_classic_2()

However, I want to make some cells bold. Is there a way to do it without editing the input dataframe? I tried to integrate cell_spec in the pipes but I can't get it to work. Does anyone have a solution?

EDIT: here is some example data. I want to make all cells bold, that are below a value of 0.05 in the brackets. Using a conditional row_spec however, does not seem to work because there are two values in the cells.

structure(list(`2012` = c("4.16 (0.02)", "1.39 (0.043)", "-3.65 (0.213)", 
"4.35 (0.248)", "3.16 (0.036)", "8.84 (0.002)", "15.13 (0)", 
"13.03 (0)", "11.16 (0.002)", "4.35 (0.047)", "-2.39 (0.6)", 
"-1.45 (0.531)"), `2013` = c("-5.97 (0.24)", "-2.45 (0.73)", 
"1.58 (0.002)", "17.77 (0)", "24.23 (0)", "17.29 (0)", "24.62 (0)", 
"26.95 (0)", "16.92 (0)", "2.53 (0.13)", "3.79 (0.019)", "4.37 (0)"
), `2014` = c("-22.53 (0.04)", "-14.01 (0.899)", "-3.06 (0.079)", 
"12.06 (0.072)", "20.32 (0.011)", "13.86 (0.009)", "34.91 (0)", 
"32.15 (0)", "27.33 (0)", "2.53 (0.412)", "3.79 (0.158)", "-6.35 (0)"
), `2012-2014` = c("-26.36 (0.002)", "-13.62 (0.028)", "-4.05 (0)", 
"34.98 (0)", "46.65 (0)", "37.45 (0)", "76.91 (0)", "77.23 (0)", 
"60.26 (0)", "-14.44 (0.004)", "-15.67 (0)", "-6.71 (0)")), class = "data.frame", row.names = c("test 3", 
"test 7", "test 15", "test1 3", "test1 7", "test1 15", 
"test3 3", "test 3", "test 4", "test 4", "test 4", "test 4"))

CodePudding user response:

column_spec can accept a vector of logical values to control text formats of individual cells in a column. This example sets cell (3, 1) to bold.

library(tidyverse)
library(kableExtra)
df <- tibble(a = 1:5, b = 1:5)
df %>%
  kbl() %>%
  column_spec(1, bold = ifelse(df$a == 3, TRUE, FALSE)) %>%
  kable_styling()

CodePudding user response:

You could use cell_spec conditionally with dplyr::mutate and stringr

library(kableExtra)
library(dplyr)
library(stringr)

pdtable |>
  mutate(across(everything(), ~cell_spec(.x, bold = ifelse(as.numeric(str_extract(.x, "(?<=\\().*?(?=\\))"))<0.05, TRUE, FALSE)))) |>
  kbl(caption = "This is the caption",
      escape = FALSE) |>
  kable_classic_2()

enter image description here

  • Related