Comments, Style, and Readability
Write clean, documented R code following the tidyverse style guide.
Single-Line Comments with #
In R, the # character starts a comment. Everything from # to the end of the line is ignored by the interpreter. Comments are for humans — explain why, not just what.
# This is a comment — R ignores it completely
x <- 42 # inline comment after code
# Bad comment (states the obvious):
y <- y + 1 # add 1 to y
# Good comment (explains intent):
y <- y + 1 # shift index to 1-based for output display
cat('x =', x)Section Headers with ------
A widely adopted R convention is to create section headers by adding at least four dashes, equal signs, or hashes after the comment text. RStudio recognizes these and adds them to the document outline for easy navigation.
# Data Loading -------------------------------------------------------
# This section loads raw CSV files from the data/ folder
# Data Cleaning =======================================================
# Remove duplicates and fix missing values
# Modeling ############################################################
# Fit linear model and evaluate
cat('Section headers improve navigation')All lessons in this course
- Using source() to Load Scripts
- Comments, Style, and Readability
- Working Directories and File Paths
- R Projects and Workspace Management