从 R 标记和 Knitr 中删除 R 输出中的哈希

我使用 RStudio 来写我的 R Markdown 文件。如何删除代码输出之前显示的最终 HTML 输出文件中的散列(##) ?

举个例子:

---
output: html_document
---


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

enter image description here

45562 次浏览

You can include in your chunk options something like

comment=NA # to remove all hashes

or

comment='%' # to use a different character

More help on knitr available from here: http://yihui.name/knitr/options

If you are using R Markdown as you mentioned, your chunk could look like this:

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

If you want to change this globally, you can include a chunk in your document:

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

Just HTML

If your output is just HTML, you can make good use of the PRE or CODE HTML tag.

Example

```{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 Result:

    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

Just PDF

If your output is PDF, then you may need some replace function. Here what I am using:

```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)
}
```

Example

The code also needs to be a little different:

```{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 Result

PDF result

PDF and HTML

If you really need the page work in both cases PDF and HTML, the tidyPrint should be a little different in the last step.

```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"))
}
```

Result

The PDF result is the same, and the HTML result is close to the previous, but with some extra border.

HTML Result in the mixed version

It is not perfect but maybe is good enough.