Object names
Spacing
if (debug) show(x)
plot(x, y)
# Bad
if(debug)show(x)
plot (x, y)
Indenting
y <- 10
x <- if (y < 20) "Too low" else "Too high"
Long lines
每行代碼宜不超過80個字元。
若代碼超出這80個字元,應儘量將一些功能打包成獨立的函數。
若代碼太長,不能寫成一行代碼,可以一行寫函數名,一行寫參數,一行寫右括號)。這樣代碼可讀性更強,也便於修改。例如:
# Good
do_something_very_complicated(
"that",
requires = many,
arguments = "some of which may be long"
)
# Bad
do_something_very_complicated("that", requires, many, arguments,
"some of which may be long"
)
若參數之間關係密切,可以將幾個參數放在同一行中,例如用paste()或stop()字符串。如有可能,生成字符串時要將一行代碼和它的輸出放到同一行中。不要把分號;放在行尾,也不要用它分隔同一行的多條命令。
# Good
paste0(
"Requirement: ", requires, "\n",
"Result: ", result, "\n"
)
# Bad
paste0(
"Requirement: ", requires,
"\n", "Result: ",
result, "\n")
Assignment
x <- 5
# Bad
x = 5
Semicolons
Quites
The tidyverse style guide
Learn the tidyverse-R for data science
CRAN-tidyverse: Easily Install and Load the 'Tidyverse'