Comments

Like any sensible programming language, R allows us to include comments in our code. The comment character in R is #. Each line preceded by at least one # symbol will be interpreted as a comment. Comments are not evaluated when you run your code. R simply ignores anything after the # character.

# This is a comment, not code
1 + 1
[1] 2
2^2 # first three characters on this line are code; the rest is a comment
[1] 4

Do: Run the following code to generate two integer vectors and print the results.

Predict: What will the following lines print?

In the code above, the expression 1:10 is “commented out”, so R doesn’t evaluate that line at all. Consequently, running the code only prints the result of the second expression, 2:8.

There are no block comments in R. So, you need to add a # character before every line when you want to create multi-line comments.

# This is a really long-winded explanation of exactly why the following is
# such a very super-duper awesome way of doing this thing that I'm trying to
# do here, because I'm a special little teapot, and I've got the very best
# ideas, and you really, really need to know about them.
x <- 1
y <- 1
z <- x + y
z
[1] 2

Why Use Comments?

Comments have two primary uses.

Use 1: Leaving short, explanatory notes to yourself (or to anyone else reading your code) about why a particular line does what it does.

# Add 2 and 2
2 + 2
[1] 4

Use 2: Temporarily disabling parts of your code that you don’t want to completely remove (e.g., for debugging).

For example, in the following code, I’m trying to accomplish a few things.

  1. Generate a \(25 \times 4\) matrix of standard normal deviates
  2. Store this matrix as an object named x.
  3. Compute the eigenvalue decomposition of x.
  4. Calculate the covariance matrix of x.

Do: Run the following code, and see what happens.

Oops…something breaks when trying to compute the eigenvalue decomposition. We’ll assume I need that result, so I don’t want to simply remove the broken line. If I’m not willing or able to fix the issue immediately, I can comment out the offending command and proceed with my work. Try it for yourself.

Do: In the interactive editor above, try commenting out the line xEigen <- eigen(x) and rerunning the code.

See: Hopefully, the code now runs. As an added benefit, the commented line acts as a marker of the bug I need to fix in the future.

Knowledge Check

Predict: What will the following code print?

5 + 5
# 5 - 5
5 * 5

Use the interactive editor to check your predictions.

Back to top