从R Markdown和Knitr中删除R输出中的哈希值

时间:2013-02-26 04:12:11

标签: r-markdown knitr

我正在使用RStudio来编写我的R Markdown文件。如何删除代码输出前显示的最终HTML输出文件中的哈希值(##)?

举个例子:

---
output: html_document
---

```{r}
head(cars)
```

enter image description here

2 个答案:

答案 0 :(得分:77)

您可以在您的块选项中包含类似

的内容
comment=NA # to remove all hashes

comment='%' # to use a different character

有关knitr的更多帮助,请点击此处:http://yihui.name/knitr/options

如果你正如你所提到的那样使用R Markdown,你的大块可能是这样的:

```{r comment=NA}
summary(cars)
```

如果要全局更改,可以在文档中包含一个块:

```{r include=FALSE}
knitr::opts_chunk$set(comment = NA)
```

答案 1 :(得分:0)

仅HTML

如果您的输出只是HTML,则可以充分利用PRE或CODE HTML标记。

示例

```{r my_pre_example,echo=FALSE,include=TRUE,results='asis'}
knitr::opts_chunk$set(comment = NA)
cat('<pre>')
print(t.test(mtcars$mpg,mtcars$wt))
cat('</pre>')
```

HTML结果:

    Welch Two Sample t-test

data: mtcars$mpg and mtcars$wt t = 15.633, df = 32.633, p-value < 0.00000000000000022 alternative hypothesis: true difference in means is not equal to 0 95 percent confidence interval: 14.67644 19.07031 sample estimates: mean of x mean of y 20.09062 3.21725

仅PDF

如果输出为PDF,则可能需要一些替换功能。这是我正在使用的:

```r
tidyPrint <- function(data) {
    content <- paste0(data,collapse = "\n\n")
    content <- str_replace_all(content,"\\t","    ")
    content <- str_replace_all(content,"\\ ","\\\\ ")
    content <- str_replace_all(content,"\\$","\\\\$")
    content <- str_replace_all(content,"\\*","\\\\*")
    content <- str_replace_all(content,":",": ")
    return(content)
  }
```

示例

代码也需要有所不同:

```{r my_pre_example,echo=FALSE,include=TRUE,results='asis'}
knitr::opts_chunk$set(comment = NA)
resultTTest <- capture.output(t.test(mtcars$mpg,mtcars$wt))
cat(tidyPrint(resultTTest))
```

PDF结果

PDF result

PDF和HTML

如果你真的需要在这两种情况下的PDF和HTML网页的工作,在tidyPrint应该是最后一步稍有不同。

```r
tidyPrint <- function(data) {
    content <- paste0(data,collapse = "\n\n")
    content <- str_replace_all(content,"\\t","    ")
    content <- str_replace_all(content,"\\ ","\\\\ ")
    content <- str_replace_all(content,"\\$","\\\\$")
    content <- str_replace_all(content,"\\*","\\\\*")
    content <- str_replace_all(content,":",": ")
    return(paste("<code>",content,"</code>\n"))
  }
```

结果

PDF结果是相同的,而HTML结果与前一个结果很接近,但是带有一些额外的边框。

HTML Result in the mixed version

这是不完美的,但也许是不够好。