sisyphlab
sisyphlab

Reputation: 11

conditionally format dynamically created table in R

I would like to render a table in R, with cells formatted according to some non-trivial logic. (e.g. if a value is odd, color the cell yellow; if it is also >5, make the text bold, etc.). This logic would be applied to each column of a dynamically created table, i.e. the column names are unknown so cannot be used in the code.

If found this JQuery approach helpful, but I'm not sure it completely solves my problem, plus I would prefer an R-based approach.

I also came close using the condformat package, but for some reason the following doesn't work:

library(condformat)
data(iris)

# Create a condformat object
cf <- condformat(iris)

# Add rules to it:
for (col in colnames(iris)[1:2]) {
  cf <- cf %>% rule_css(!!col, 
expression = ifelse(eval(parse(text=col)) < 3.3, "red", "black"),
css_field = 'color')
}
# Render it
cf

The first column of the resulting table doesn’t abide by the rule; instead, it is given the colors from column 2. But if I instead loop over just that first column, the coloring for it is correct.

Any help with the above code, or with the problem generally, would be greatly appreciated.

Upvotes: 1

Views: 662

Answers (2)

Soeren D.
Soeren D.

Reputation: 352

In order to do this on a dynamic table, you could loop over the columns of the data.frame like this (taking most of the code from Ozan147's answer):

library(kableExtra)

test <- iris[1:10, ]


for(i in 1:ncol(test)){

  if(is.numeric(test[[i]])){
      test[[i]] <- cell_spec(
                      test[[i]], 
                     "html", 
                      background = ifelse(test[[i]] %% 2 == 1, "yellow", "red"),
                      bold = ifelse(test[[i]] > 5, T, F)
                     )
  }
}

test %>%
  kable(format = "html", escape = F) %>%
  kable_styling("striped", full_width = F)

Upvotes: 0

ozanstats
ozanstats

Reputation: 2864

kableExtra is a very powerful tool for creating HTML tables in R.

library(kableExtra)

iris[1:10, 1:2] %>% 
  mutate(
    Sepal.Length = cell_spec(
      Sepal.Length, 
      "html", 
      background = ifelse(Sepal.Length %% 2 == 1, "yellow", "red"),
      bold = ifelse(Sepal.Length > 5, T, F)
    ),
    Sepal.Width = cell_spec(
      Sepal.Width, 
      "html", 
      background = ifelse(Sepal.Width %% 2 == 1, "blue", "green"),
      bold = ifelse(Sepal.Width > 10, T, F)
    ),
  )  %>%
  kable(format = "html", escape = F) %>%
  kable_styling("striped", full_width = F)

Please refer to the documentation for additional details:
Create Awesome HTML Table with knitr::kable and kableExtra

Upvotes: 1

Related Questions