Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide comments in R markdown

Is is possible to hide some comments in code when kniting using knitr / R markdown? Example:

---
title: "SOSO"
author: "SO"
date: '2017-06-06'
output: pdf_document


---

```{r}

# Generate some data

rnorm(2)

## But keep this comment

```

When kniting I would like the first comment to disapear, but keep the second one somehow.

like image 411
MLEN Avatar asked Jun 06 '17 20:06

MLEN


People also ask

How do I hide messages in R Markdown?

Hide source code: ```{r, echo=FALSE} 1 + 1 ``` Hide text output (you can also use `results = FALSE`): ```{r, results='hide'} print("You will not see the text output.") ``` Hide messages: ```{r, message=FALSE} message("You will not see the message.") ``` Hide warning messages: ```{r, warning=FALSE} # this will generate ...

How do I show output in R Markdown?

If you prefer to use the console by default for all your R Markdown documents (restoring the behavior in previous versions of RStudio), you can make Chunk Output in Console the default: Tools -> Options -> R Markdown -> Show output inline for all R Markdown documents .


Video Answer


1 Answers

Here is a quick example of modifying the hook to change knitr behavior.

---
title: "SOSO"
author: "SO"
date: 2017-06-06
output: pdf_document
---

```{r setup-hook, echo=FALSE}
hook_in <- function(x, options) {
    x <- x[!grepl("^#\\s+", x)]
    paste0("```r\n",
          paste0(x, collapse="\n"),
          "\n```")
}
knitr::knit_hooks$set(source = hook_in)
```

```{r}

# Generate some data
# Lines that starts with `# ` will be removed from the rendered documents

rnorm(2)

## But keep this comment
## But lines that starts with `## ` will be kept

```

produces thisenter image description here

like image 132
sinQueso Avatar answered Sep 23 '22 15:09

sinQueso