使用 kable 根据关闭值为一行元素着色

Using kable to color a row of elements based off value

knitr::kable(pen_financials_matrix,
             align = c("l", "l", "c", "c", "c", "c"),
             caption = "Financial Report (Sorted by Pen Number)")%>%
  kable_styling(bootstrap_options = "striped")

使用此代码(请参阅下面的 pen_financials_matrix 定义)我创建了这个 table:

pen_financial_matrix 是一个数据框,其中包含给定的每支笔的值列。在图片中您可以看到列出了 9 种不同的笔,但这个数字可能会根据给定的数据而变化。

我正在尝试将某些行的文本颜色更改为红色或绿色。例如,“总 IOFC”大于 0 时应为绿色,小于 0 时应为红色。

我了解如何使用 column_spec() 为列着色,但我不知道如何在一行中引用值。

dput(pen_financials_matrix)
structure(list(Variables = c("Pen Milk Income", "Pen Feed Cost", 
"Feed Efficiency", "Nitrogen Efficiency", "Feed Saved or Wasted", 
"Feed Cost / Cwt of Milk", "Total IOFC"), Units = c("$/day", 
"$/day", "NE Milk / NE Feed,%", "Milk N / Feed N, %", "$/pen/day", 
"(Pen Feed$/Pen milk) * 100", "Milk Income - Feed Cost"), `1` = c("96.48", 
"72", "1.27", "22.88", "0.798", "78.64", "24.48"), `2` = c("3440.41", 
"1672", "1.95", "31.24", "0.761", "51.21", "1768.41"), `3` = c("1199.66", 
"664", "1.71", "26.92", "0.093", "58.33", "535.66"), `4` = c("1638.10", 
"888", "1.75", "29.94", "0.794", "57.12", "750.10"), `5` = c("1155.19", 
"808", "1.36", "24.59", "0.380", "73.71", "347.19"), `7` = c("407.65", 
"312", "1.24", "23.48", "0.505", "80.65", "95.65"), `78` = c("171.45", 
"120", "1.36", "25.10", "0.426", "73.75", "51.45"), `88` = c("763.56", 
"456", "1.59", "27.76", "0.223", "62.93", "307.56"), `98` = c("763.56", 
"456", "1.59", "27.76", "0.223", "62.93", "307.56")), class = "data.frame", row.names = c(NA, 
-7L))

这里要使用的中心函数是kableExtra::cell_spec,它“被设计为在data.frame进入kable函数之前使用”。由于我想不出另一种在“整洁”管道中使用它的方法,我建议使用以下包装函数:

conditionalColor <- function(x, row, columnOffset, threshold, colorLarger, colorElse) {
  x[row, (columnOffset+1):ncol(x)] <- cell_spec(
    x[row, (columnOffset+1):ncol(x)], 
    color = ifelse(as.numeric(x[row, (columnOffset+1):ncol(x)]) < threshold, 
                   colorLarger, 
                   colorElse))
  return(x)
}

这会为 x 中一个 row 的所有单元格中的文本着色,条件是单元格值大于 (colorLarger) 大于 threshold 或不大于 (colorElse), 忽略直到 columnOffset.

的列

请注意,cell_spec 向数据添加了标记。因此,在kable.

中设置escape = FALSE

示例用法 与问题中定义的对象 pen_financials_matrix:突出显示“总 IOFC”行中的单元格(如果 > 100 则为绿色,否则为红色):

conditionalColor(pen_financials_matrix, 
                 row = which(pen_financials_matrix[ , 1] == "Total IOFC"), 
                 columnOffset = 2, 
                 threshold = 100, colorLarger = "green", colorElse = "red") %>% 
  knitr::kable(escape = FALSE) %>%
  kable_styling(bootstrap_options = "striped")

输出:

一般来说,我认为如果数据被转置使得变量在列而不是行中,这会更容易。那么就可以了