How to set knitr::kable() global options in markdown for reuse
Asked Answered
L

1

16

Is there an easy to use way to setup custom default kable() options, so that there is no need in rewriting them for each kable() call.

For example, my usual table styling uses following code:

library(kableExtra)
kable(mtcars, booktabs=TRUE, digits= 2) %>% kable_styling(latex_options =c("striped", "scale_down"))

I would like to set all kable() kable_styling options so that a call to kable(mtcars) with no arguments defaults to my usual table styling.

Libidinous answered 13/1, 2019 at 11:48 Comment(0)
T
23

Just write your own function to do that:

kable <- function(data) {
  knitr::kable(data, booktabs = TRUE, digits = 2) %>% 
    kable_styling(latex_options =c("striped", "scale_down"))
}

It might be less confusing to give it a new name instead of masking kable; that's up to you.

Tammy answered 13/1, 2019 at 16:23 Comment(5)
When I use such a function, I lose the ability of additional arguments such as col.names from kable. How to deal with this? Also, the answer doesn't make it clear whether or not the question from OP is actually possible, since this is a workaround.Deron
@FLonLon: Your first question is a different issue; you should ask a new question about that. The tricky bit will be identifying whether additional arguments belong to knitr::kable or to kable_styling; be specific in what sort of options you have in mind when you post your question. Your final statement is just plain wrong. This does exactly what this questioner asked.Tammy
Thank you. As for the second part, no it does not. The question asks for setting global options, you answered with a custom function. This is not the same. Global options are even addressed here bookdown.org/yihui/rmarkdown-cookbook/… but don't work for me, which is why I landed here.Deron
@FLonLon: Please see en.wikipedia.org/wiki/XY_problem .Tammy
Since the OP accepted your question, I assume that this was an XY porblem. The title and the google result however is about the global settings. this is precisely why I said that the answer should specify "doing this with global options (a.k.a. your "X") is not possible, but you can achieve Y with this custom function". Because when you come here with that question, you leave with a solution, but the question unanswered. I'm not involved in SE philosophy, but I ususally expect an answer even if it means saying that X was the wrong thing to ask / is not possible.Deron

© 2022 - 2024 — McMap. All rights reserved.