R Comments
Comments let you annotate R code with explanations that the interpreter ignores when running your program.
Single-Line Comments
In R, anything after a # symbol on a line is a comment and is ignored by the interpreter. Comments can sit on their own line or follow working code on the same line.
Example
# This line calculates a total
total <- 10 + 5 # inline comment explaining the result
print(total)Why Use Comments?
- Explain why code does something, not just what it does
- Leave notes for your future self or teammates
- Temporarily disable a line of code while testing
- Document assumptions about the data or the analysis
No True Multi-Line Comment
R does not have a dedicated multi-line comment syntax like /* ... */ found in some other languages. Every commented line needs its own # symbol. Most editors, including RStudio, let you select several lines and comment them all out at once with a keyboard shortcut.
Example
# Step 1: create the data
# Step 2: clean the data
# Step 3: summarize the data
data <- c(1, 2, 3)
print(sum(data))Commenting Out Code
Adding a # in front of a line of working code is a common way to temporarily disable it without deleting it, which is useful while debugging or trying an alternate approach.
Exercise: R Comments
Which character starts a single-line comment in R?