【问题标题】:Conditional formatting for strings with grep in kable在 kable 中使用 grep 对字符串进行条件格式设置
【发布时间】:2019-06-25 15:01:46
【问题描述】:

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

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”列中的数值。

【问题讨论】:

    标签: r kable


    【解决方案1】:

    使用grepl 而不是grep,因为grepl 返回一个逻辑向量,而grep 返回匹配索引,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")
    

    【讨论】:

      【解决方案2】:

      根据?ifelse,用法是

      ifelse(测试,是,否)

      和

      test - 可以强制转换为逻辑模式的对象。

      使用grep,根据?grep返回数字索引

      value - 如果为 FALSE,则返回一个包含由 grep 确定的匹配项的(整数)索引的向量,如果为 TRUE,则返回一个包含匹配元素本身的向量。

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

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

      替换(x,列表,值)

      list - 一个索引向量

      -代码

      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")
      

      -输出

      【讨论】:

        猜你喜欢
        • 2020-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-27
        • 2015-10-29
        • 2020-04-29
        相关资源
        最近更新 更多