r_code

R 代码风格书写

李家翔 2019-01-23

参考irudnyts

函数命名用动词 Naming Function

# Good
add()

# Bad
addition()

大括号的书写方式 Curly braces

# Good 
if (is_used) {
  # do something
}

if (is_used) {
  # do something
} else {
  # do something else
}

# Bad
if (is_used)
{
  # do something
}

if (is_used) { # do something }
else { # do something else }

缩进 Indentation

There are two common number of spaces for indentation: two (Hadley and others) and four (Bioconductor). My own rule of thumb: I use four spaces indentation for data analyses scripts, and two spaces while developing packages.

在做数据分析的时候,建议用4个空格的缩进,保持 R 和 Python 的统一。

换行 New line

# Good 
normal_pdf <- 1 / sqrt(2 * pi * d_sigma ^ 2) *
  exp(-(x - d_mean) ^ 2 / 2 / s ^ 2)

# Bad
normal_pdf <- 1 / sqrt(2 * pi * d_sigma ^ 2)
  * exp(-(x - d_mean) ^ 2 / 2 / d_sigma ^ 2)

R 对于 Bad 的例子中,* exp(-(x - d_mean) ^ 2 / 2 / d_sigma ^ 2)没有识别。