How to force outputs of both text/html and text/latex?

Jupyter/R’s default display of a data.frame generates both text/html and text/latex versions as outputs. You can see both explicitly described in the JSON-format .ipynb file. (This is great because the html version is nicely rendered in the running Jupyter notebook, while the latex version can be used when converting from .ipynb to .tex format).

To specially format data.frames, I use knitr’s kable function, which produces either html (rendered in Jupyter) OR latex (not rendered in Jupyter). How can I force output of BOTH, like the default display does.

The JSON-format .ipynb file should look something like this:

“cell_type”: “code”,
“execution_count”: 12,
“metadata”: {
“hide_input”: false
},
“outputs”: [
{
“data”: {
“text/html”: [
“<table class="dataframe">\n”, …
],
“text/latex”: [
“A data.frame: 3 × 3\n”,
“\begin{tabular}{lll}\n”, …
]
},
“metadata”: {},
“output_type”: “display_data”
}
],
“source”: [
“data.frame(a=c(1,2,3), b=c(10,20,30), c=c(100,200,300))”
]
},

Here’s the solution. Use kable to create an HTML representation and use kable again to create a LaTex representation. Build a “mimebundle” list with these two representations as elements. Use IRdisplay’s publish_mimebundle function to display. The HTML representation will be rendered when running Jupyter; the LaTex representation will be copied as-is by pandoc when converting from Jupyter-format to LaTeX format.

x = data.frame(a=c(1,2,3), b=c(10,20,30), c=c(100,200,300))
x.html = kable(x, format=“html”, escape=FALSE, align=rep(“r”, ncol(x)), caption=“This is from HTML”, row.names=FALSE, table.attr=“style="white-space: nowrap;"”)
x.latex = kable_styling(latex_options=c(“hold_position”),
kable(x, format=“latex”, escape=FALSE, align=rep(“r”, ncol(x)), caption=“This is from LaTex”, row.names=FALSE))
mbx = list(data=list(“text/html”=as.character(x.html), “text/latex”=as.character(x.latex)), metadata=NULL)
publish_mimebundle(mbx$data, mbx$metadata)

1 Like