This is my very first posting on Stack Overflow, so please forgive me if this is an ill-formed or non-reproducible question. I am attempting to pass the following custom data table printing function ('print.me') to the YAML header in RMarkdown for df_print knitting to HTML:
print.me <- function(x) {
x <- x %>% kbl(digits=2, align= 'l', booktabs=T) %>%
kable_styling(fixed_thead = T, position ="float_right") %>%
kable_paper("striped", full_width = T, fixed_thead = T,
html_font = "Helvetica", font_size = 11) %>%
row_spec(0, color = "yellow", background = "#5b705f", font_size = 12) %>%
scroll_box(width = "700px", height = "300px")
return(x)
}
This function successfully renders the dataframe format I am hoping for when printing mtcars from RMarkdown:
The problem is that I cannot figure out a way to successfully pass 'print.me' to the YAML header so that 'print.me' becomes the default method of rendering dataframes when knitting to HTML. My code in the YAML header looks like:
df_print: !expr 'print.me'
However, I receive the following error message:
Error: object 'print.me' not found Error in yaml::yaml.load(..., eval.expr = TRUE) : Could not evaluate expression: print.me Calls: ... parse_yaml_front_matter -> yaml_load -> Execution halted
The df_print
documentation claims that it is possible to pass an arbitrary function to df_print
, and I have found a past post that seems to have reached a workaround, but I cannot for the life of me figure out how to call this function from the header. Thanks for any help! ~ Jamie
I couldn't find this in the rmarkdown documentation but I don't think it's recommended to pass a complex function like yours to the df_print
argument in the YAML header. However, according to this issue on GitHub for (a simplified version of) print.me()
it goes like this:
---
title: "testprint"
output:
html_document:
df_print: !expr print.me <- function(x, ...) { knitr::asis_output(kableExtra::kbl(x, digits=2, align= 'l'))}
---
Instead, you may register your own method for printing dataframes in a code chunk (preferably right after the YAML header) like this:
```{r setup, include=FALSE}
library(kableExtra)
library(knitr)
print.me <- function(x, ...) {
x %>%
kbl(digits=2, align= 'l', booktabs=T) %>%
kable_styling(fixed_thead = T, position ="float_right") %>%
kable_paper("striped", full_width = T, fixed_thead = T,
html_font = "Helvetica", font_size = 11) %>%
row_spec(0, color = "yellow", background = "#5b705f", font_size = 12) %>%
scroll_box(width = "700px", height = "300px") %>%
asis_output()
}
registerS3method("knit_print", "data.frame", print.me)
```
The technical details are a bit complicated. In short, we overwrite the default function that is called upon checking the class of the object to be printed (geeks call this procedure method dispatch) with the custom function and register this method to knitr.