Multiline Comment Workarounds?

RCommentsR Faq

R Problem Overview


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?

R Solutions


Solution 1 - R

You can do this easily in RStudio:

select the code and click CTR+SHIFT+C to comment/uncomment code.

Solution 2 - R

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

Solution 3 - R

A neat trick for RStudio I've just discovered is to use #' as this creates an self-expanding comment section (when you return to new line from such a line or insert new lines into such a section it is automatically comment).

Solution 4 - R

[Update] Based on comments.

# An empty function for Comments
Comment <- function(`@Comments`) {invisible()}

#### Comments ####
Comment( `

  # Put anything in here except back-ticks.
  
  api_idea <- function() {
    return TRUE
  }
  
  # Just to show api_idea isn't really there...
  print( api_idea )

`)
####

#### Code. ####
foo <- function() {
  print( "The above did not evaluate!")
}
foo()

[Original Answer]

Here's another way... check out the pic at the bottom. Cut and paste the code block into RStudio.

Multiline comments that make using an IDE more effective are a "Good Thing", most IDEs or simple editors don't have highlighting of text within simple commented -out blocks; though some authors have taken the time to ensure parsing within here-strings. With R we don't have multi-line comments or here-strings either, but using invisible expressions in RStudio gives all that goodness.

As long as there aren't any backticks in the section desired to be used for a multiline comments, here-strings, or non-executed comment blocks then this might be something worth-while.

#### Intro Notes & Comments ####
invisible( expression( `
{ <= put the brace here to reset the auto indenting...
  
  Base <- function()
  {      <^~~~~~~~~~~~~~~~ Use the function as a header and nesting marker for the comments
         that show up in the jump-menu.
         --->8---
  }
  
  External <- function()
  {
    If we used a function similar to:
      api_idea <- function() {
        
        some_api_example <- function( nested ) {
          stopifnot( some required check here )
        }
        
        print("Cut and paste this into RStudio to see the code-chunk quick-jump structure.")
        return converted object
      }
    
    #### Code. ####
    ^~~~~~~~~~~~~~~~~~~~~~~~~~ <= Notice that this comment section isnt in the jump menu!
                                  Putting an apostrophe in isn't causes RStudio to parse as text
                                  and needs to be matched prior to nested structure working again.
    api_idea2 <- function() {
    
    } # That isn't in the jump-menu, but the one below is...
    
    api_idea3 <- function() {
    
    }
    
  }
    
    # Just to show api_idea isn't really there...
    print( api_idea )
    }`) )
####

#### Code. ####
foo <- function() {
  print( "The above did not evaluate and cause an error!")
}

foo()

## [1] "The above did not evaluate and cause an error!"

And here's the pic...

Structured Comments

Solution 5 - R

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

}

Solution 6 - R

If find it incredible that any language would not cater for this.

This is probably the cleanest workaround:

anything="
first comment line
second comment line
"

Solution 7 - R

Apart from using the overkilled way to comment multi-line codes just by installing RStudio, you can use Notepad++ as it supports the syntax highlighting of R

(Select multi-lines) -> Edit -> Comment/Uncomment -> Toggle Block Comment

Note that you need to save the code as a .R source first (highlighted in red)

Note that you need to save the code as a .R source first (highlighted in red)

Solution 8 - R

I use vim to edit the R script.

Let's say the R script is test.R, containing say "Line 1", "Line 2", and "Line 3" on 3 separate lines.

I open test.R on the command line with Vim by typing "vim test.R". Then I go to the 1st line I want to comment out, type "Control-V", down arrow to the last line I want to comment out, type a capital I i.e. "I" for insert, type "# ", and then hit the Escape key to add "# " to every line that I selected by arrowing down. Save the file in Vim and then exit Vim by typing ":wq". Changes should show up in Rstudio.

To delete the comments in Vim, start at the first line on top of the character "#" you want to delete, again do "Control-V", and arrow down to the last line you want to delete a "#" from. Then type "dd". The "#" signs should be deleted.

There's seconds-worth of lag time between when changes to test.R in Vim are reflected in Rstudio.

Solution 9 - R

Now there is a workaround, by using package ARTofR or bannerCommenter

Examples here:

enter image description here

Solution 10 - R

In RStudio an easy way to do this is to write your comment and once you have used CTRL + Shift + C to comment your line of code, then use CTRL + SHIFT + / to reflow you comment onto multiple lines for ease of reading.

Solution 11 - R

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHamiltonUlmerView Question on Stackoverflow
Solution 1 - RSalvador DaliView Answer on Stackoverflow
Solution 2 - RDirk EddelbuettelView Answer on Stackoverflow
Solution 3 - RgeotheoryView Answer on Stackoverflow
Solution 4 - RThellView Answer on Stackoverflow
Solution 5 - RThierryView Answer on Stackoverflow
Solution 6 - RR. SakeView Answer on Stackoverflow
Solution 7 - Rim_chcView Answer on Stackoverflow
Solution 8 - RQian ZhangView Answer on Stackoverflow
Solution 9 - RHuanyuan ZhangView Answer on Stackoverflow
Solution 10 - RMark StevensonView Answer on Stackoverflow
Solution 11 - Ruser5099519View Answer on Stackoverflow