← Back to R Course | Chapter 12: Best Practices | Lesson 1 of 6

Writing Clean R Code

Clean R code is neat and easy to read, like a tidy bedroom where you can find everything. It uses clear names, sensible spacing, and helpful notes.

In this page:

  1. Writing Clean R Code

Writing Clean R Code

Clean R code uses consistent, descriptive names (typically snake_case or camelCase), keeps functions focused on one task, and avoids deeply nested logic where a helper function would read more clearly.

Comments should explain intent, not restate obvious code. Following a consistent style, like the tidyverse style guide, makes code easier for others (and future you) to read.

Note: Pick one naming convention (snake_case is the R community's most common choice) and use it consistently throughout a project.

Example: Writing Clean R Code

markup
# Clear, descriptive names and a focused function
calculate_average_score <- function(scores) {
  mean(scores, na.rm = TRUE)
}

student_scores <- c(85, 90, NA, 78)
cat("Average:", calculate_average_score(student_scores), "\n")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Naming variables with single letters like x1 and df2, when descriptive names show what the data means.
  2. Mixing naming styles such as calculateScore and student_scores, when one style should be used.
  3. Writing long functions that do many things, when short focused functions are easier to test.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.