我有一个函数可以输出正确呈现的html代码,但是将它包含在一个降价文档R代码块中,带有'result =“asis”`失败。我将问题追溯到HTML代码中的空格。我喜欢这些空格,因为它们使得更容易阅读原始HTML文件。如果你愿意考虑安装我的R包“rockchalk”,你可以运行它并看到相同的内容。
我在下面的MRE中显示问题是由HTML中的空格(markdown视为代码的标记)引起的。我得到的输出没有任何额外的样式表魔法可用:http://pj.freefaculty.org/scraps/mre.html
向下滚动,你看到桌子坏了,但是在筛出多余的空格后,表格会按预期显示。
在您看来,这仅仅是我依赖HTML代码中的空格的用户错误,还是R markdown中“asis”中的错误。
---
title: "Guide Documents"
author:
- name: Paul Johnson
affiliation: Center for Research Methods and Data Analysis, University of Kansas
abstract:
Author, please REMEMBER TO INCLUDE AN ABSTRACT BEFORE FINALIZING THIS DOCUMENT!
date: "`r format(Sys.time(), '%Y %B %d')`"
output:
html_document:
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}
library(rockchalk)
set.seed(2134234)
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"}
cat(or1)
```
```{r cleaned, results = "asis"}
or1 <- gsub(" "," ", or1)
or1 <- gsub("^\\ *", "", or1)
or1 <- paste(or1, collapse = "")
or1 <- gsub("\\ \\ \\ \\ \\ \\ ", " ", or1)
or1 <- gsub("\\ \\ \\ ", " ", or1)
cat(or1)
```
```{r sessionInfo, echo = FALSE}
sessionInfo()
```
Available under
[Created Commons license 3.0 <img src="http://crmda.dept.ku.edu/images/cc-3.0.png" alt="CC BY"
style="width: 75px;height: 20px;"/>](http://creativecommons.org/licenses/by/3.0/)
答案 0 :(得分:4)
knitr 块选项results='asis'
已正确完成其工作。问题是Pandoc's Markdown将缩进行(四个空格)视为文字代码块(<pre></pre>
)。
解决方案是移除前导空格或保护它们。看来你不想做前者。您可以将HTML代码传递给htmltools::HTML()
,以便在Pandoc转换期间保护输出。