How to comment blocks of R code in R markdown?

I am editing an R markdown (.Rmd) file that has many R code blocks in order to move the groups of these code blocks into β€œchild” documents in order to simplify partition reordering (if nothing else). When I convert sections to child documents, I would like to test a new child document without the rest of the blocks and other children. However, when I use these sections for comments, the R-blocks still work (but RStudio makes the sections β€œlook” as if they were commented out).

If I exclude previous and trailing "` `` `s (i.e. code denominators), commenting works fine. However, as I said, I have many blocks of code, and something seems more convenient.

So, how can I comment on R code blocks so that they don't start?

+5
source share
2 answers

In RStudio, if you select (at least) one line above the R code block before (at least) the last line of the R code snippet , 1 and then type ctrl-shift-C (on OSX or Windows) or Command-shift-C (OSX only), RStudio will place the html comment tags in a piece.

For instance:

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

After highlighting this and entering ctrl-shift-C, this will become the following:

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

To selectively comment on several fragments, you can use the RStudio search / replace tool with the regex option. It takes two replacement steps (maybe this can be done in one step, but I'm not sure how to make a regular expression to capture multiple lines in RStudio).

Step 1: Comment on the first line of one or more fragments:

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

Step 2: Comment on the last line of one or more fragments:

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


1 You must include a line above the fragment in the selected fragment. Otherwise, RStudio will place R-tag ( # ) tags at the beginning of each line of the block, and commented lines will be displayed as plain text in the output document.

+6
source

In the Rmarkdown document, we can apply certain parameters to each fragment of the R code, which determines whether the code will be executed, printed inside, output error messages, etc.

To not execute a specific piece of code, use:

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

To prevent a specific piece of code from starting or printing in the created document, use:

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

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

If you have a lot of code snippets that you need to comment on, you can accept the offer from @ eipi10 (thanks) and use find / replace with the regex option selected. Thus, the find will be "(` `` {r. *) ", And the replacement will be" \ 1, eval = FALSE, echo = FALSE} "(without double quotes).

+4
source

Source: https://habr.com/ru/post/1271541/


All Articles