kableExtra
kableExtra copied to clipboard
Allow `column_spec` to receive column names as well as numbers
Hello,
I like the approach of column_spec
, but I don't like the fact you can only specify columns by numbers. If I ever reorder a table, I have to remember to go back and edit all column_spec
calls accordingly (I'm lazy / forgetful and this is easily something I could not notice).
I realise that you need the column numbers for dealing with xml in functions like column_spec_html
, but I think you could add some juggling early on in column_spec
itself to allow the user to use column names. Something like adding the argument to feed in the orginal data frame, and then using match
:
column_spec <- function (kable_input, column, original_data = NULL, width = NULL, bold = FALSE, italic = FALSE,
monospace = FALSE, underline = FALSE, strikeout = FALSE,
color = NULL, background = NULL, border_left = FALSE, border_right = FALSE,
width_min = NULL, width_max = NULL, extra_css = NULL, include_thead = FALSE,
latex_column_spec = NULL, latex_valign = "p", link = NULL,
new_tab = TRUE, tooltip = NULL, popover = NULL, image = NULL)
{
if (!is.numeric(column) & is.null(original_data)) {
stop("column must be numeric if original data not supplied.")
}
if (!is.numeric(column) & !is.null(original_data)){
column <- match(column, names(original_data))
}
This will allow the user to do stuff like.
inline_plot %>%
kbl(booktabs = TRUE) %>%
kable_paper(full_width = FALSE) %>%
column_spec("mpg_box", original_data = inline_plot, image = spec_boxplot(mpg_list)) %>%
column_spec(3, image = spec_hist(mpg_list)) %>%
column_spec(4, image = spec_plot(mpg_list, same_lim = TRUE)) %>%
column_spec(5, image = spec_plot(mpg_list, same_lim = FALSE)) %>%
column_spec(6, image = spec_plot(mpg_list, type = "p")) %>%
column_spec(7, image = spec_plot(mpg_list, disp_list, type = "p")) %>%
column_spec(8, image = spec_plot(mpg_list, polymin = 5))
Of course they can do it manually themselves before calling column_spec
, but I think it's nice for them if it's incorporated into the function itself.
It would also be nice to use some quasiquotation to allow the user to avoid having to use quotes, even better if it allows the user to avoid having to wrap the names in c()
when modifying multiple columns - i.e. let them do something like: column_spec(mpg_box, mpg_hist, ...)
. But I guess that's a fair bit more involved and the above is a pretty trivial modification (I think).
It's a shame that column_spec
doesn't know about the piped data frame as then we could even drop the original_data
argument as well for the super super lazy users (like me).
What do you think?