如何用 formattable/ kableextra 修改 table 行的样式

how to modify the style of a row of a table with formattable/ kableextra

我有 table 这样的酒吧 (what I have)。 我的问题是我希望最后一行没有颜色条(比如 default:with 只有数字)

image of the code

data(mtcars)

library(knitr)
library(kableExtra)
library(formattable)
library(dplyr)
library(stringr)

mtcars[1:5, 1:4] %>%
  mutate(
    car = row.names(.),
    mpg = color_bar("lightgreen")(mpg),
    cyl = color_bar("lightgreen")(cyl),
    disp = color_bar("lightgreen")(disp),
    hp = color_bar("lightgreen")(hp)
  ) %>%
  select(car, everything()) %>%
  kable("html", escape = F) %>%
  kable_styling("hover", full_width = F) %>%
  column_spec(5, width = "3cm") 

提前致谢

调用 color_bar("lightgreen") 给出了一个函数,该函数在背景中设置带有条形图的向量的格式。因此,如果您只想格式化第一部分,请编写您自己的函数,以这种方式只格式化第一个 n-1 条目。例如:

my_color_bar <- function(color) {
  mainpart <- color_bar(color)
  function(x) {
    start <- x[-length(x)]
    last <- x[length(x)]          
    c(mainpart(start), last)
  }
}

然后使用该函数而不是原始函数生成 table:

mtcars[1:5, 1:4] %>%
        mutate(
                car = row.names(.),
                mpg = my_color_bar("lightgreen")(mpg),
                cyl = my_color_bar("lightgreen")(cyl),
                disp = my_color_bar("lightgreen")(disp),
                hp = my_color_bar("lightgreen")(hp)
        ) %>%
        select(car, everything()) %>%
        kable("html", escape = FALSE) %>%
        kable_styling("hover", full_width = FALSE) %>%
        column_spec(5, width = "3cm")