使用条件语句 (case_when) 跨多列更改 kableExtra 中的单元格颜色

Change cell colour in kableExtra across multiple columns using conditional statements (case_when)

我有一个 table 和多个 character 变量(命名为 First、Second 等)。每个变量都包含许多可能的字符串(例如“DBP”、“Low PA”) .我想为这些字符串中的每一个分配一个背景颜色(例如“DBP”或“SBP = red,“Low PA”= blue)。

我希望这是一个 mutate 语句,而不是为每一列编写单独的 case_when 语句:

    ```{r table1,}
df1 = data.frame(year = c(2014, 2015, 2011, 2013),
                 outcome = c("decline", "death", "death or decline", "decline"),
                 "First" = c("DBP", "Cholesterol", "Low PA", "CRP"),
                 "Second" =  c("SBP", "CRP",NA ,NA ),
                  "Third" = c("Low PA", "SBP", NA, NA))
df1 = data.frame(lapply(df1, as.character), stringsAsFactors=FALSE)
df1[is.na(df1)] = ""
df1%>%
  kbl("latex", longtable = TRUE, escape = F, booktabs =  T)%>%
  mutate(across(c(3:5)), column_spec (., background = case_when(. == "SBP" ~ "red",
                                                                    . == "Low PA" ~ "blue",
                                                                    . =="CRP" ~ "gray",
                                                                    TRUE ~ "white")) )%>%
  kable_styling(latex_options= c( "repeat_header"), font_size =10,repeat_header_method =  "replace")

这是我试过的一个例子。为此我得到错误: UseMethod("mutate") 错误:没有适用于 'mutate' 的方法应用于 class“knitr_kable”的对象。

以下代码适用于一列(“第一”)

df1%>%
  kbl("latex", longtable = TRUE, escape = F, booktabs =  T)%>%
  column_spec(3 , background = case_when(df1$First == "DBP" ~ "red",
                                                df1$First == "SBP" ~ "red",
                                                df1$First == "Low PA" ~ "blue",
                                                df1$First =="CRP" ~ "gray",
                                                TRUE ~ "white"))%>%
  kable_styling(latex_options= c( "repeat_header"), font_size =10, repeat_header_method =  "replace")

实现您想要的结果的一个选择是使用 purrr::reduce(或来自基础 R 的 Reduce),如下所示:

df1 %>%
  kbl("latex", longtable = TRUE, escape = F, booktabs = T) %>%
  purrr::reduce(3:5, function(x, y) {
    col <- df1[, y]
    column_spec(x, y, background = case_when(
      col == "SBP" ~ "red",
      col == "Low PA" ~ "blue",
      col == "CRP" ~ "gray",
      TRUE ~ "white"))
  }, .init = .) %>%
  kable_styling(latex_options = c("repeat_header"), font_size = 10, repeat_header_method = "replace")