Search code examples
rdplyrknitrkableextraformattable

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


I have bar table like that (what I have). My problem is that I would like the last row to be without color-bar (like by default:with only the number )

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

Thank you in advance


Solution

  • The call color_bar("lightgreen") gives a function that formats a vector with the bar in the background. So if you want to format only the first part, write your own function that only formats the first n-1 entries that way. For example:

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

    Then produce the table using that function instead of the original one:

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