[R] How to comment in R

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Wed Feb 11 12:35:16 CET 2009

(Ted Harding) wrote:
> If a comment extends
> over several lines, each one needs a "#". However, as has been
> suggested, various text editors make it easier to do that. For
> example, in 'vim':
> 1: Type in the several lines of comment (without "#"). Press 'Esc'.
> 2. With the cursor in the first line, press 'Shift'+'V'.
> 3. Move the cursor down to the last line, thus highlighting all.
> 4. Then type
>    :s/^/# /
>    and each line will then start with "# ". (It's very quick once
> you are used to it).

but not all is lost for those that do not use smart editors that know
how to r-comment blocks of code.  using a simple sed command, one can
automatically comment and uncomment parts of code enclosed between some
custom r-commented tags, e.g., '#start' and '#end':

# sample file with start-end comment tags
cat <<END > foo.r
f = function(...) {
    args = list(...)
    #start commenting everything until the closest #end
    # a comment that will remain a comment after uncommenting commented code
    b1 =
    a1 = g(b1,
    #end commenting

# comment out blocks between start-end tags
sed '/^\s*#start/,/^\s*#end/{/^\s*#\(start\|end\)/!s/^/#/}' foo.r >

# uncomment blocks between start-end tags
sed '/^\s*#start/,/^\s*#end/{/^\s*#\(start\|end\)/!s/^#//}'
foo-commented.r > foo-uncommented.r

# check for differences
diff foo.r foo-uncommented.r


More information about the R-help mailing list