Search code examples
htmlrr-markdownoutputcomments

How can I exclude comments in the knit output in Rmarkdown?


I'm quite new to R and even newer to Rmarkdown so please forgive me if this is an idiotic question. I would like to exclude the comments I have put into my code blocks from the html output after knitting without excluding the actual working code. Here's an example of a block:

```{r, echo=TRUE}
#Read data, remove unnecessary columns, rename the necessary ones and convert to a tibble
data <- read_dta("assignment1.dta") %>%
  select(datestr, GDPC1) %>%
  rename(Date=datestr, GDP=GDPC1) %>%
  mutate(Date = as.Date(Date)) %>%
  as_tibble()
```

So here, I would like to exclude #Read data, remove unnecessary columns, rename the necessary ones and convert to a tibble from the html output and include the rest. And would I have to specify at the start of each block or could I define it at the start of the doc here?

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

I hope I have described my issue well enough for you fine folk to understand!

I consulted ChatGPT who told me to just preface every block as such:

```{r, echo=TRUE, comment=""}
#Comment I don't want displayed
print("Hello, world!")
```

It still displayed the comment!


Solution

  • If your document isn't huge and you just want to preserve some comments, you can just do:

    ```{r, echo=-1, comment=""}
    #Comment I don't want displayed
    print("Hello, world!")
    ```
    

    enter image description here

    Or, if you have a span of comments:

    ```{r, echo=4:5, comment=""}
    #Comment I don't want displayed
    # I don't want this displayed either
    # or this
    print("Hello, world!")
    print("Goodbye, world!")
    ```