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

Writing Clean R Code

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")
🔒

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.