向 Rmarkdown 中输出的分数之一添加条件

Add a condition to one of the scores output in Rmarkdown

我正在使用 Rmarkdown 将一些可读性分数作为 table 输出,并且想知道是否有任何方法可以向其中一行添加条件 "if the score is greater or equal to 14 then output the colour as red otherwise green" 以下是生成示例数据的代码:

FGL <- 16
    Readability_score <- data.frame(Type = c("SMOG","Flesch Reading Ease","Flesch-Kincaid Grade Level", 
                                         "Gunning Fog Score", "Automated Readability Index"), 
                                Score = c(17,23,FGL,22, 19))

这是使用 Rmarkdown 在 html 中输出 table 的代码:

    kable(Readability_score, "html") %>%
  kable_styling(bootstrap_options = "striped", full_width = F, position = "left") %>%
  row_spec(3, bold = T, color = "white", background = "grey")

如果分数大于 14,我希望数据框的第三个元素以红色突出显示(Flesch-Kincaid 等级,16)。 到目前为止,我尝试将 cell_spec() 与以下代码一起使用,但无法使其正常工作

FGL <- 16

Readability_score <- data.frame(Type = c("SMOG","Flesch Reading Ease","Flesch-Kincaid Grade Level", 
                                         "Gunning Fog Score", "Automated Readability Index"), 
                                Score = c(17,23,cell_spec(FGL, "html", color = ifelse(FGL >= 14, "red", "green")),22, 19))

也许在这里使用 cell_spec() 不是一个好主意。关于实现我在这里想要实现的目标的方法的任何其他建议,或者如果有人可以指出我的代码中的任何错误 - 将非常有帮助,谢谢。

PS。 运行 上述代码:需要以下包

library("dplyr")
library("knitr")
library("kableExtra")

你只需要在 kable 函数中设置 escape=F 参数

library("dplyr")
library("knitr")
library("kableExtra")

FGL <- 16

Readability_score <- data.frame(Type = c("SMOG",
                                     "Flesch Reading Ease",
                                     "Flesch-Kincaid Grade Level", 
                                     "Gunning Fog Score", 
                                     "Automated Readability Index"), 
                            Score = c(17,23,
                                      cell_spec(FGL, "html", 
                                                      color = ifelse(FGL >= 14, "red", "green")),22, 19))

在下面的行中 escape=F 添加到您已经编写的代码中

kable(Readability_score, "html", escape = F) %>%
  kable_styling(bootstrap_options = "striped", full_width = F, position = "left")