0Pricing
R Academy · Lesson

Comments, Style, and Readability

Write clean, documented R code following the tidyverse style guide.

Comments, Style, and Readability is a free R Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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')

snake_case Naming Convention

The tidyverse style guide recommends snake_case for all object names: lowercase words separated by underscores. Avoid dots (which look like method calls in other languages) and camelCase for consistency.

# Good: snake_case
user_age <- 25
monthly_revenue <- 15000
calculate_mean <- function(x) mean(x)

# Avoid: dots in names (looks like OOP method calls)
user.age <- 25       # confusing

# Avoid: camelCase (inconsistent with tidyverse)
userAge <- 25

# Avoid: ALL_CAPS (reserved for true constants by convention)
MAX_RETRIES <- 3     # acceptable for config constants only

cat('snake_case wins')

Spaces Around Operators

Always put spaces around assignment and comparison operators. This dramatically improves readability. The one exception is inside function argument lists where = binds argument names.

# Good: spaces around <- and operators
x <- 10
y <- x + 5
result <- x * y - 2
is_valid <- x > 0 & y < 100

# Bad: cramped
x<-10
y<-x+5

# Function arguments: = without extra spaces is fine
mean(x = c(1, 2, 3), na.rm = TRUE)

# Comparison operators also need spaces
if (x > 0) cat('positive')
if (x >= 0 & y <= 100) cat('in range')

Use <- Not = for Assignment

Although R allows = for assignment at the top level, the strong community convention is to use <- for object assignment and reserve = exclusively for function argument values. This distinction makes code much easier to read at a glance.

# Correct: <- for assignment
name <- 'Alice'
score <- 95.5
results <- c(1, 2, 3)

# Correct: = inside function calls
round(3.14159, digits = 2)
read.csv('data.csv', header = TRUE, sep = ',')

# Avoid: = for top-level assignment
# name = 'Alice'   <- works but not idiomatic

cat('Assignment convention:', name, score)

The 80-Character Line Limit

Keeping lines under 80 characters ensures code is readable in split-pane editors, printed pages, and code review tools. In RStudio you can display a margin guide at column 80 via Tools → Global Options → Code → Display.

# Bad: one very long line (hard to read)
result <- some_function(argument_one = 'value', argument_two = 100, argument_three = TRUE, argument_four = 'long_string')

# Good: break at commas, indent continuation
result <- some_function(
  argument_one   = 'value',
  argument_two   = 100,
  argument_three = TRUE,
  argument_four  = 'long_string'
)

cat('Readable at 80 chars')

No Semicolons

Unlike JavaScript or C, R does not require semicolons at the end of statements. Semicolons can be used to put multiple statements on one line, but the style guide says: one statement per line, no semicolons.

# Bad: semicolons and multiple statements per line
x <- 1; y <- 2; z <- x + y

# Good: one statement per line
x <- 1
y <- 2
z <- x + y

# The semicolon form is only acceptable in very short
# interactive throwaway code, never in scripts
cat('z =', z)

Readable Variable Names

Choose names that are descriptive without being excessively long. A good rule: if you have to think for more than a second to understand a variable name six months later, it is too short or too cryptic.

# Too cryptic:
d <- read.csv('data.csv')
tmp <- d[d$v1 > 0, ]
r <- lm(v2 ~ v1, data = tmp)

# Good names:
sales_data    <- read.csv('data.csv')
positive_rows <- sales_data[sales_data$revenue > 0, ]
revenue_model <- lm(profit ~ revenue, data = positive_rows)

# Avoid abbreviations that are not universally understood:
# n_obs is fine (number of observations)
# nrv is not (nobody knows what this is)

cat('Names tell the story')

Curly Braces and Indentation

The tidyverse style guide specifies: opening brace { on the same line, closing brace } on its own line. Use 2 spaces for indentation (not tabs). Consistent indentation is critical for reading nested logic.

# Good style: brace on same line, 2-space indent
if (x > 0) {
  cat('positive\n')
} else {
  cat('non-positive\n')
}

# Good function definition:
calculate_bmi <- function(weight_kg, height_m) {
  bmi <- weight_kg / height_m^2
  round(bmi, 1)
}

cat('BMI:', calculate_bmi(70, 1.75))

Spacing Inside Brackets and Commas

Put a space after every comma (like in English writing), but no space before a comma or immediately inside brackets. This mirrors mathematical notation and makes indexing easy to read.

# Good: space after comma, not before
x <- c(1, 2, 3, 4, 5)
m <- matrix(1:9, nrow = 3, ncol = 3)

# Subsetting: no space before [ or inside []
first_row <- m[1, ]      # good
value     <- m[2, 3]    # good

# Bad:
# c(1,2,3)     <- no space after comma
# m[ 1, ]      <- space after [
# m[1 , ]      <- space before comma

cat('Spacing is consistent')

Using styler and lintr

Two tools automate style enforcement in R. styler reformats your code to match the tidyverse style guide. lintr statically checks your code for style and potential errors without running it. Both integrate with RStudio.

# styler: reformat a file automatically
# install.packages('styler')
# styler::style_file('my_script.R')

# styler: reformat the whole project
# styler::style_dir('R/')

# lintr: check for style and potential bugs
# install.packages('lintr')
# lintr::lint('my_script.R')

# lintr reports issues like:
#   line 10: [object_name_linter] Variable 'myVar' should use snake_case
#   line 15: [spaces_around_ops_linter] No space before '<-'

cat('Style tools: styler + lintr')

Quick Check

According to the tidyverse style guide, which of the following is the correct way to write an assignment statement in R?

Style and Readability — Key Takeaways

Well-styled R code is professional, maintainable, and collaborative:

  • # for comments — explain why, not just what
  • Section headers with ------ or ====== for navigation
  • snake_case for all object and function names
  • Spaces around <-, +, ==, etc.
  • Use <- for assignment, = only in function arguments
  • Max 80 characters per line — break long calls across lines
  • No semicolons — one statement per line
  • 2-space indentation, opening { on same line
  • Use styler to auto-format, lintr to detect issues
# Putting it all together:

# Calculate summary statistics ----------------------------------------
calculate_summary <- function(values, remove_na = TRUE) {
  cleaned <- values[!is.na(values)]
  list(
    mean   = mean(cleaned),
    median = median(cleaned),
    sd     = sd(cleaned)
  )
}

test_scores <- c(85, 90, NA, 78, 92, 88)
stats <- calculate_summary(test_scores)
cat('Mean:', stats$mean, '\n')
cat('SD:  ', stats$sd)

Frequently asked questions

Is the “Comments, Style, and Readability” lesson free?

Yes — the full text of “Comments, Style, and Readability” is free to read here on the web, and the R Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the R Academy course, upgrade to CoddyKit PRO.

What will I learn in “Comments, Style, and Readability”?

Write clean, documented R code following the tidyverse style guide. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start R Academy?

No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Comments, Style, and Readability” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this R Academy lesson?

Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Using source() to Load Scripts
  2. Comments, Style, and Readability
  3. Working Directories and File Paths
  4. R Projects and Workspace Management
← Back to R Academy