pauljohn32 pauljohn32 - 1 year ago 84
R Question

R markdown asis breaks valid html code

I have a function that outputs html code that renders properly, but encasing it in a markdown document R code chunk with ┬┤results = "asis"` fails. I trace problem back to spaces in my HTML code. I like the spaces because they make it easier to read the raw HTML file. If you would please consider installing my R package "rockchalk", you could run this and see the same.

I show the problem is caused by spaces in HTML (which markdown treats as markup for code) in the following MRE. The output I get without any additional style sheet magic is available:

You scroll down you see the table is broken, but after sifting out the extra spaces, then the table shows as intended.

In your opinion, is this simply my user error for relying on spaces in HTML code, or is it a bug in "asis" in R markdown.

title: "Guide Documents"
- name: Paul Johnson
affiliation: Center for Research Methods and Data Analysis, University of Kansas

date: "`r format(Sys.time(), '%Y %B %d')`"
highlight: haddock

```{r setup, include = FALSE}
##This Invisible Chunk is required in all CRMDA documents
outdir <- paste0("tmpout")
if (!file.exists(outdir)) dir.create(outdir, recursive = TRUE)
knitr::opts_chunk$set(echo = TRUE, comment = NA, fig.path = paste0(outdir, "/p-"))
options(width = 70)

```{r myregs}
dat <- data.frame(x1 = rnorm(100), x2 = rnorm(100))
dat$y1 <- 30 + 5 * rnorm(100) + 3 * dat$x1 + 4 * dat$x2
dat$y2 <- rnorm(100) + 5 * dat$x2
m1 <- lm(y1 ~ x1, data = dat)
m2 <- lm(y1 ~ x2, data = dat)
m3 <- lm(y1 ~ x1 + x2, data = dat)
gm1 <- glm(y1 ~ x1, family = Gamma, data = dat)
or1 <- outreg(list("Amod" = m1, "Bmod" = m2, "Gmod" = m3),
title = "My Three Linear Regressions", float = FALSE, type = "html")

```{r browseme}
or1 <- outreg(list("Amod" = m1, "Bmod" = m2, "Gmod" = m3),
title = "My Three Linear Regressions", float = FALSE, type = "html")

```{r flawed, results = "asis"}

```{r cleaned, results = "asis"}
or1 <- gsub("&nbsp;"," ", or1)
or1 <- gsub("^\\ *", "", or1)
or1 <- paste(or1, collapse = "")
or1 <- gsub("\\ \\ \\ \\ \\ \\ ", " ", or1)
or1 <- gsub("\\ \\ \\ ", " ", or1)

```{r sessionInfo, echo = FALSE}

Available under
[Created Commons license 3.0 <img src="" alt="CC BY"
style="width: 75px;height: 20px;"/>](

Answer Source

The knitr chunk option results='asis' has done its job correctly. The problem is Pandoc's Markdown treats indented lines (by four spaces) as literal code blocks (<pre></pre>).

The solution is either remove the leading spaces, or protect them. It seems you do not want to do the former. You can pass your HTML code to htmltools::HTML() so that the output is protected during Pandoc's conversion.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download