Remove Hashes in R Output from R Markdown and Knitr

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

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