在 kable 中使用 grep 对字符串进行条件格式化

Conditional formatting for strings with grep in kable

使用 cell_spec 可以根据值有条件地格式化 kable table 中的数字单元格,但是有没有办法根据字符串中的模式格式化单元格?

library(dplyr)
library(kableExtra)

df <- data.frame(x = c("bbb", "bba", "bbb"), y = c(-7, -7, 7)) %>%
  mutate(x = cell_spec(x, "html", color = ifelse(grep("a", x), "red", "black"))) %>%
  mutate(y = cell_spec(y, "html", color = ifelse(y < 0, "red", "black")))

kable(df, "html", escape = F) %>%
  kable_styling("striped")

在上面的代码中使用 grep 将整个列变为红色,而我希望只有包含 "a" 的单元格为红色。此过程适用于列 "y" 中的数值。

使用 grepl 而不是 grep 作为 grepl returns 逻辑向量,而 grep returns 匹配索引和 ifelse 需要一个逻辑向量 .

library(dplyr)
library(kableExtra)

df <- data.frame(x = c("bbb", "bba", "bbb"), y = c(-7, -7, 7)) %>%
 mutate(x = cell_spec(x, "html",color = ifelse(grepl("a", x), "red", "black"))) %>%
 mutate(y = cell_spec(y, "html", color = ifelse(y < 0, "red", "black")))


kable(df, "html", escape = F) %>% kable_styling("striped")

根据?ifelse,用法是

ifelse(test, yes, no)

test - an object which can be coerced to logical mode.

使用grep,根据?grep

返回数值索引

value - if FALSE, a vector containing the (integer) indices of the matches determined by grep is returned, and if TRUE, a vector containing the matching elements themselves is returned.

所以,ifelse 'test' 的输入肯定与 grep 的输出不匹配。

如果我们想用grep,我们可以用replace,这里的用法是

replace(x, list, values)

list - an index vector

-代码

library(kableExtra)
library(dplyr)
df <- data.frame(x = c("bbb", "bba", "bbb"), y = c(-7, -7, 7)) %>%
     mutate(x = cell_spec(x, "html", 
               color = replace(rep("black", n()), grep("a", x), "red")), 
            y = cell_spec(y, "html", 
               color = ifelse(y < 0, "red", "black")))

kable(df, "html", escape = F) %>% kable_styling("striped")

-输出