R: Comment out block of code

RComments

R Problem Overview


> Possible Duplicate:
> R: Multiline Comment Workarounds?

I want to comment out several lines of code in R. Is there any way of doing it without having to put a # before each line - sort of like /* blocked out code */ in SAS?

R Solutions


Solution 1 - R

Most of the editors take some kind of shortcut to comment out blocks of code. The default editors use something like command or control and single quote to comment out selected lines of code. In RStudio it's Command or Control+/. Check in your editor.

It's still commenting line by line, but they also uncomment selected lines as well. For the Mac RGUI it's command-option ' (I'm imagining windows is control option). For Rstudio it's just Command or Control + Shift + C again.

These shortcuts will likely change over time as editors get updated and different software becomes the most popular R editors. You'll have to look it up for whatever software you have.

Solution 2 - R

A sort of block comment uses an if statement:

if(FALSE) {
  all your code
}

It works, but I almost always use the block comment options of my editors (RStudio, Kate, Kwrite).

Solution 3 - R

Wrap it in an unused function:

.f = function() {

## unwanted code here:

}

Solution 4 - R

I use RStudio or Emacs and always use the editor shortcuts available to comment regions. If this is not a possibility then you could use Paul's answer but this only works if your code is syntactically correct.

Here is another dirty way I came up with, wrap it in scan() and remove the result. It does store the comment in memory for a short while so it will probably not work with very large comments. Best still is to just put # signs in front of every line (possibly with editor shortcuts).

foo <- scan(what="character")
These are comments
These are still comments
Can also be code:
x <- 1:10
One line must be blank

rm(foo)

Solution 5 - R

I have dealt with this at talkstats.com in posts 94, 101 & 103 found in the thread: Share Your Code. As others have said Rstudio may be a better way to go. I store these functions in my .Rprofile and actually use them a but to automatically block out lines of code quickly.

Not quite as nice as you were hoping for but may be an approach.

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
Questionuser702432View Question on Stackoverflow
Solution 1 - RJohnView Answer on Stackoverflow
Solution 2 - RPaul HiemstraView Answer on Stackoverflow
Solution 3 - RmdsumnerView Answer on Stackoverflow
Solution 4 - RSacha EpskampView Answer on Stackoverflow
Solution 5 - RTyler RinkerView Answer on Stackoverflow