7

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.

1
  • 3
    You could write a custom output hook that removes lines based on whatever criteria you would like. Commented Jun 6, 2017 at 20:25

2 Answers 2

13

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

Sign up to request clarification or add additional context in comments.

1 Comment

This strategy does not seem to work if sourcing from a separate R script using knitr::read_chunk
6

In fact, you can choose to show any lines of R code by passing numeric indices to the chunk option echo, e.g.

--- title: "SOSO" author: "SO" date: '2017-06-06' output: pdf_document --- ```{r echo=4:7} # Generate some data rnorm(2) ## But keep this comment ``` 

See knitr documentation for more information.

1 Comment

This is a far more elegant solution than the accepted answer. Though the accepted answer is quite clever.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.