Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

r - Passing columns to kableExtra arguments within dplyr

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

question from:https://stackoverflow.com/questions/66048468/passing-columns-to-kableextra-arguments-within-dplyr

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...