Multiline Comment Workarounds?

Viewed 60911

I (sort of) already know the answer to this question. But I figured it is one that gets asked so frequently on the R Users list, that there should be one solid good answer. To the best of my knowledge there is no multiline comment functionality in R. So, does anyone have any good workarounds?

While quite a bit of work in R usually involves interactive sessions (which casts doubt on the need for multiline comments), there are times when I've had to send scripts to colleagues and classmates, much of which involves nontrivial blocks of code. And for people coming from other languages it is a fairly natural question.

In the past I've used quotes. Since strings support linebreaks, running an R script with

"
Here's my multiline comment.

"
a <- 10
rocknroll.lm <- lm(blah blah blah)
 ...

works fine. Does anyone have a better solution?

11 Answers

This does come up on the mailing list fairly regularly, see for example this recent thread on r-help. The consensus answer usually is the one shown above: that given that the language has no direct support, you have to either

  • work with an editor that has region-to-comment commands, and most advanced R editors do
  • use the if (FALSE) constructs suggested earlier but note that it still requires complete parsing and must hence be syntactically correct

I can think of two options. The first option is to use an editor that allows to block comment and uncomment (eg. Eclipse). The second option is to use an if statement. But that will only allow you to 'comment' correct R syntax. Hence a good editor is the prefered workaround.

if(FALSE){
     #everything in this case is not executed

}

In RStudio you can use a pound sign and quote like this:

#' This is a comment

Now, every time you hit return you don't need to add the #', RStudio will automatically put that in for you.

Incidentally, for adding parameters and items that are returned, for standardization if you type an @ symbol inside those comment strings, RStudio will automatically show you a list of codes associated with those comment parameters:

#' @param tracker_df Dataframe of limit names and limits
#' @param invoice_data Dataframe of invoice data
#' @return return_list List of scores for each limit and rejected invoice rows
Related