Remove Hashes in R Output from R Markdown and Knit

2019-03-10 14:27发布

问题:

I am using RStudio to write my R Markdown files. How can I remove the hashes (##) in the final HTML output file that are displayed before the code output?

As an example:

---
output: html_document
---

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

回答1:

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


回答2:

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 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.

It is not perfect but maybe is good enough.