TExcelTAD
Home › R › R Comments

R Comments

A comment is text that R ignores. Comments explain why code does something, leave notes for your future self, or temporarily switch code off.

In R, a comment starts with # and runs to the end of the line:

r · try it yourself
# Convert a distance from miles to kilometres
miles <- 26.2          # a marathon
km <- miles * 1.609344
km
[1] 42.16481

Multi-line comments

R has no special block-comment syntax. To comment several lines, start each one with #. Most editors do this for you: in RStudio press Ctrl+Shift+C to toggle comments on the selected lines.

r · try it yourself
# This script computes the area of a circle.
# Input:  radius r (in metres)
# Output: area in square metres
r <- 3
area <- pi * r^2
round(area, 2)
[1] 28.27

Note: You may see people "comment out" a block with if (FALSE) { ... }. The code inside must still be valid R, so plain # lines are usually the better choice.

Commenting out code

Putting # in front of a line is a quick way to disable it while you test something:

r · try it yourself
prices <- c(3.5, 8, 12.25)
# prices <- prices * 1.2    # VAT disabled for now
sum(prices)
[1] 23.75

# inside strings is not a comment

A # inside quotes is just a character:

r · try it yourself
tag <- "#rstats"   # the first # is part of the string
tag
nchar(tag)
[1] "#rstats"
[1] 7

Writing good comments

  • Explain why, not what. x <- x * 1.609344 # miles to km is useful; x <- x * 2 # multiply x by 2 is noise.
  • Keep comments up to date: a wrong comment is worse than none.
  • Use a header comment at the top of a script that says what it does and what data it expects.
  • Section headers like # ---- Load data ---- are folded into an outline by RStudio.

Documentation comments

Packages document functions with roxygen comments, which start with #' and use @ tags. Tools turn them into help pages:

r
#' Convert Celsius to Fahrenheit
#'
#' @param celsius A numeric vector of temperatures.
#' @return The temperatures in Fahrenheit.
to_fahrenheit <- function(celsius) {
  celsius * 9 / 5 + 32
}

To R itself these are ordinary comments.

Test yourself

Which character starts a comment in R?

  1. //
  2. #
  3. --
  4. %

How do you write a comment that spans three lines?

  1. /* ... */
  2. """ ... """
  3. Start each line with #
  4. <!-- ... -->

What does nchar("a#b") return?

  1. 1
  2. 3
  3. 0
  4. An error