how to comment out R code blocks in R markdown?

I'm editing an R markdown file (.Rmd) that has a lot of R code blocks to move groups of those code blocks into "child" documents to simplify rearranging sections (if nothing else). As I convert sections to child documents, I would like to test the new child document without running the rest of the blocks and other children. However, when I use to comment out those sections, the R blocks still run (but RStudio makes the sections "look" as though they were commented out).

If I eliminate the preceding and trailing "```"s (ie, the code block signifiers), the commenting works fine. However, as I said, I've got lots of code blocks and something like would be more convenient.

So, how do I comment out the R code blocks so they won't run?


In RStudio, if you highlight from (at least) one row above an R code chunk to (at least) the last row of the R code chunk ,1 and then type ctrl-shift-C (in OSX or Windows) or command-shift-C (OSX only), RStudio will place html comment tags on the chunk.

For example:

```{r cars}
summary(cars)
plot(pressure)
```

After highlighting this and type ctrl-shift-C, this becomes:

<!-- ```{r cars} -->
<!-- summary(cars) -->
<!-- plot(pressure) -->
<!-- ``` -->

To selectively comment out multiple chunks, you can use the RStudio find/replace tool with the regex option checked. It takes two replacement steps (it can probably be done in one step, but I'm not sure how to do a regex to capture across multiple lines in RStudio).

Step 1: Comment out the first line of one or more chunks:

Find: (```{r.*)
Replace: <!--1

Step 2: Comment out the last line of one or more chunks:

Find: (```)$
Replace: 1-->


1 You must include the row above the chunk in the highlight. Otherwise, RStudio will place R comment tags ( # ) at the beginning of each row of the chunk and the commented lines will appear as plain text in the output document.


In an Rmarkdown document, we can apply certain options to each R code chunk that determines whether the code inside will be run, printed, show error messages, etc.

To have a specific code chunk not run, use:

```{r cars, eval=FALSE}
summary(cars)
```

To have a specific code chunk not run or print into the created doc, use:

```{r cars, eval=FALSE, echo=FALSE}
summary(cars)
```

"TRUE" is used for the opposite effects and is the default.

If you have many code chunks you need to comment out, you can take the suggestion from @eipi10 (thanks) and use find/replace with the regex option selected. So, the find would be "(```{r.*)", and the replace would be "1, eval=FALSE, echo=FALSE}" (without the double quotes).

链接地址: http://www.djcxy.com/p/20150.html

上一篇: 如何在Github Flavored Markdown中添加内联评论?

下一篇: 如何评论R markdown中的R代码块?