Passing columns to kableExtra arguments within dplyr

Viewed 356

I'm trying to use kable and kableExtra to format tables created using pipes, and I can't get the conditional formatting arguments (row_spec, column_spec) to accept variables piped from the generated code.

In the toy example below I create a variable called bg within the dataframe that I want to use to create bands of background colour, but row_spec and column_spec don't seem to recognize that as a variable. Note that creating the variable outside of the pipes isn't an option - the actual use case is much more complicated than that, and the variables used in the process don't exist before that.


library(kableExtra)
set.seed(111)

df = data.frame(var1 = sort(sample(LETTERS[1:3],10,TRUE)),
                var2 = sample(1:4,10,TRUE),
                var3 = runif(10,0,1))
df %>%
  mutate(bg = cumsum(!duplicated(var1))%%2)%>%
  kable() %>%kable_styling()%>%
  column_spec(1,color=bg)

Error in ensure_len_html(color, nrows, "color") : object 'bg' not found

EDIT: You can do it in two steps easily enough, so I'll include that here, as well as the resulting table that I'm looking for

d = df %>%
  mutate(bg = cumsum(!duplicated(var1))%%2)
kable(d) %>% kable_styling(full_width=FALSE) %>% 
  row_spec(which(d$bg==1),background=grey(0.75))

enter image description here

1 Answers

This might work:

library(tidyverse)
library(kableExtra)

set.seed(111)
df = data.frame(var1 = sort(sample(LETTERS[1:3],10,TRUE)),
                var2 = sample(1:4,10,TRUE),
                var3 = runif(10,0,1))

df %>%
  mutate(bg = cumsum(!duplicated(var1))%%2) %>%
  mutate(bg = cell_spec(bg, color = spec_color(bg))) %>%
  kable(escape = F) %>% kable_styling()

Output:

enter image description here

You may find more information here (page 16): https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf

Version with background color:

df %>%
  mutate(bg = cumsum(!duplicated(var1))%%2) %>%
  mutate(bg = cell_spec(bg, color = "white", bold = T,
                        background = spec_color(bg))) %>%
  kable(escape = F) %>% kable_styling()

Output with background color:

enter image description here

Related