Comments and Code Style
Prerequisites: Functions
A comment is a note for humans; R ignores everything after a # on a
line.
# Load the survey results
tax_rate <- 0.2 # UK standard rate
RStudio comments or uncomments selected lines with Ctrl + Shift + C.
What to comment
Clear names explain what code does. Comments are for why:
# Bad: repeats the code
x <- x * 1.2 # multiply x by 1.2
# Good: explains a decision
# Responses before March used a 1-5 scale; rescale to 1-10 to match.
early$score <- early$score * 2
Script sections
In RStudio, a comment ending in four or more dashes creates a section you can jump to and fold:
# Load data ----
# Clean data ----
# Analysis ----
Style in brief
The widely followed tidyverse style guide recommends:
snake_casenames:mean_height, notmeanHeightormean.height.<-for assignment.- Spaces around operators (
x <- y + 1) and after commas. - Two-space indentation.
- Lines under about 80 characters.
The styler package reformats code to this style automatically, and the lintr package flags style issues and likely mistakes.
What's next
You now know enough R to analyze real data. Try the Beginner Projects, then continue to Level 2 — Intermediate, which starts with importing data.