注释、风格与可读性
遵循 tidyverse 风格指南,编写整洁且有文档的 R 代码
注释、风格与可读性 是 CoddyKit 上的免费 R Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 R Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 R Academy 课程共包含 4 节课。
使用 # 编写单行注释
在 R 中,# 字符用于开始注释。从 # 到行末的所有内容都会被解释器忽略。注释是写给人看的——请解释为什么,而不只是解释做什么。
# 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)使用 ------ 设置章节标题
R 中广泛采用的一种约定是:在注释文本后添加至少四个短横线、等号或井号,以创建章节标题。RStudio 能识别这些标题,并将其添加到文档大纲中,方便导航。
# 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 命名约定
tidyverse 风格指南建议所有对象名称使用 snake_case:单词全部小写,并使用下划线分隔。为保持一致性,请避免使用点号(在其他语言中点号看起来像方法调用)和 camelCase。
# 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')运算符两侧的空格
请始终在赋值和比较运算符两侧加空格。这样可以显著提高可读性。唯一的例外是在函数参数列表中,此时 = 用于绑定参数名称。
# 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')赋值使用 <-,而不是 =
虽然 R 允许在顶层使用 = 进行赋值,但社区普遍约定使用 <- 为对象赋值,并将 = 专门用于函数参数值。这样一眼就能更容易读懂代码。
# 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)每行最多 80 个字符
将每行限制在 80 个字符以内,可以确保代码在分栏编辑器、打印页面和代码审查工具中都易于阅读。在 RStudio 中,您可以通过工具 → 全局选项 → 代码 → 显示在第 80 列显示边距参考线。
# 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')不要使用分号
与 JavaScript 或 C 不同,R不要求在语句末尾使用分号。虽然可以使用分号将多条语句写在同一行,但风格指南规定:每行一条语句,不使用分号。
# 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)可读的变量名称
请选择具有描述性但不过分冗长的名称。一条实用规则是:如果六个月后看到某个变量名称时,需要思考超过一秒才能理解它,那么这个名称就太短或太晦涩了。
# 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')花括号与缩进
tidyverse 风格指南规定:左花括号 { 与代码位于同一行,右花括号 } 单独占一行。缩进使用 2 个空格,不要使用制表符。统一的缩进对于阅读嵌套逻辑至关重要。
# 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))括号和逗号内的空格
每个逗号后都要加一个空格(类似英文书写),但逗号前以及括号内部紧邻括号的位置不要加空格。这种写法与数学记号一致,也让索引更易于阅读。
# 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')使用 styler 和 lintr
有两个工具可以自动执行 R 的风格规范。styler 会按照 tidyverse 风格指南重新格式化代码。lintr 会在不运行代码的情况下,对其进行静态检查,以发现风格问题和潜在错误。两者都能与 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')快速检查
根据 tidyverse 风格指南,以下哪一种写法是 R 中正确的赋值语句?
风格与可读性——要点总结
风格良好的 R 代码专业、易维护且便于协作:
- 使用
#添加注释——解释为什么,而不只是解释做什么 - 使用
------或======设置章节标题,便于导航 - 所有对象和函数名称使用
snake_case - 在
<-、+、==等运算符两侧加空格 - 使用
<-进行赋值,=仅用于函数参数 - 每行最多 80 个字符——将较长的调用拆分到多行
- 不使用分号——每行一条语句
- 使用 2 个空格缩进,左
{与代码位于同一行 - 使用 styler 自动格式化,使用 lintr 检测问题
# 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)常见问题解答
「注释、风格与可读性」课时是免费的吗?
是的 — 「注释、风格与可读性」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 R Academy 课程的其余内容,请升级到 CoddyKit PRO。 R Academy 课程共包含 4 节课。
「注释、风格与可读性」这节课中我会学到什么?
遵循 tidyverse 风格指南,编写整洁且有文档的 R 代码 你通过在浏览器中直接运行的动手代码来练习 R Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 R Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 R Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「注释、风格与可读性」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 R Academy 课中编写并运行代码吗?
能。每节 R Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 使用 source() 加载脚本
- 注释、风格与可读性
- 工作目录与文件路径
- R 项目与工作区管理