Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 79921c8

Browse files
committed
Merge pull request ktaranov#4 from eshcherbakova/patch-1
Create R style guide and name convention.md
2 parents 6544847 + 21c1e65 commit 79921c8

File tree

1 file changed

+259
-0
lines changed

1 file changed

+259
-0
lines changed

‎R style guide and name convention.md

Lines changed: 259 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,259 @@
1+
# R name convention
2+
3+
| Object | Notation | Length | Plural | Prefix | Suffix | Abbreviation | Mask | Example |
4+
|----------------------|:-------------:|--------:|:--------:|:--------:|:--------:|:------------:|:-----------|:---------------------|
5+
| File Name | lowercase | 30 | No | No | .R | No | [a-z_]+\.R | predict_ad_revenue.R |
6+
| Function Name | PascalCase | 30 | No | No | No | No | [A-z]+ | CalculateAvgClicks |
7+
| Variable Name | camelCase | 30 | No | No | No | No | [A-z]+ | avgClicks |
8+
| Data Frame | PascalCase | 30 | No | df_ | No | No | df_[A-z]+ | df_AvgClicks |
9+
| Factor Variable Name | PascalCase | 30 | No | f | No | No | f[A-z]+ | fAvgClicks |
10+
11+
## Notation and Naming
12+
13+
### File Names
14+
15+
File names should end in .R, delimeter '\_', lowercase notation and, of course, be meaningful.
16+
17+
**GOOD:** predict\_ad\_revenue.R
18+
**BAD:** foo.R
19+
20+
### Identifiers
21+
22+
Don't use underscores ( _ ) or hyphens ( - ) in identifiers. Identifiers should be named according to the following conventions. Variable names have initial lower case letters. If variable name consists of several words, then they aren't separated, but all words except for the first one begin with capital letters. Function names are formed like variable names but with initial capital letter (FunctionName); constants are named like functions but with an initial k.
23+
- variableName
24+
** GOOD:** avgClicks
25+
**BAD:** avg_Clicks
26+
- FunctionName
27+
** GOOD:** CalculateAvgClicks
28+
** BAD:** calculate_avg_clicks , calculateAvgClicks
29+
Make function names verbs.
30+
*Exception: When creating a classed object, the function name (constructor) and class should match (e.g., lm).*
31+
- kConstantName
32+
33+
## Syntax
34+
35+
### Line Length
36+
37+
The maximum line length is 80 characters.
38+
39+
### Indentation
40+
41+
When indenting your code, use two spaces. Never use tabs or mix tabs and spaces.
42+
*Exception: When a line break occurs inside parentheses, align the wrapped line with the first character inside the parenthesis.*
43+
44+
### Spacing
45+
46+
Place spaces around all binary operators (=, +, -, <-, etc.).
47+
*Exception: Spaces around ='s are optional when passing parameters in a function call.*
48+
49+
Do not place a space before a comma, but always place one after a comma.
50+
51+
**GOOD:**
52+
```
53+
df_TabPrior <- table(df[df$days.from.opt < 0, "campaign.id"])
54+
total <- sum(x[, 1])
55+
total <- sum(x[1, ])
56+
```
57+
**BAD:**
58+
```
59+
df_TabPrior <- table(df[df$days.from.opt<0, "campaign.id"]) # Needs spaces around '<'
60+
df_TabPrior <- table(df[df$days.from.opt < 0,"campaign.id"]) # Needs a space after the comma
61+
df_TabPrior<- table(df[df$days.from.opt < 0, "campaign.id"]) # Needs a space before <-
62+
df_TabPrior<-table(df[df$days.from.opt < 0, "campaign.id"]) # Needs spaces around <-
63+
total <- sum(x[,1]) # Needs a space after the comma
64+
total <- sum(x[ ,1]) # Needs a space after the comma, not before
65+
```
66+
Place a space before left parenthesis, except in a function call.
67+
68+
**GOOD:**
69+
```
70+
if (debug)
71+
```
72+
**BAD:**
73+
```
74+
if(debug)
75+
```
76+
Extra spacing (i.e., more than one space in a row) is okay if it improves alignment of equals signs or arrows (<-).
77+
```
78+
plot (x = x.coord,
79+
y = dataMat[, MakeColName(metric, ptiles[1], "roiOpt")],
80+
ylim = ylim,
81+
xlab = "dates",
82+
ylab = metric,
83+
main = (paste(metric, " for 3 samples ", sep = "")))
84+
```
85+
Do not place spaces around code in parentheses or square brackets.
86+
*Exception: Always place a space after a comma.*
87+
88+
**GOOD:**
89+
```
90+
if (debug)
91+
x[1, ]
92+
```
93+
**BAD:**
94+
```
95+
if ( debug ) # No spaces around debug
96+
x[1,] # Needs a space after the comma
97+
```
98+
### Curly Braces
99+
100+
An opening curly brace should never go on its own line; a closing curly brace should always go on its own line. You may omit curly braces when a block consists of a single statement; however, you must consistently either use or not use curly braces for single statement blocks.
101+
**GOOD:**
102+
```
103+
if (is.null(ylim)) {
104+
ylim <- c(0, 0.06)
105+
}
106+
107+
xor (but not both)
108+
if (is.null(ylim))
109+
ylim <- c(0, 0.06)
110+
```
111+
Always begin the body of a block on a new line.
112+
113+
**BAD:**
114+
```
115+
if (is.null(ylim)) ylim <- c(0, 0.06)
116+
if (is.null(ylim)) {ylim <- c(0, 0.06)}
117+
```
118+
Surround "else" with braces.
119+
120+
An "else" statement should always be surrounded on the same line by curly braces.
121+
**GOOD:**
122+
```
123+
if (condition) {
124+
one or more lines
125+
} else {
126+
one or more lines
127+
}
128+
```
129+
**BAD:**
130+
131+
```
132+
if (condition) {
133+
one or more lines
134+
}
135+
else {
136+
one or more lines
137+
}
138+
```
139+
**BAD:**
140+
```
141+
if (condition)
142+
one line
143+
else
144+
one line
145+
```
146+
### Assignment
147+
148+
Use <-, not =, for assignment.
149+
150+
**GOOD:**
151+
```
152+
x <- 5
153+
```
154+
**BAD:**
155+
```
156+
x = 5
157+
```
158+
### Semicolons
159+
160+
Do not terminate your lines with semicolons or use semicolons to put more than one command on the same line. (Semicolons are not necessary, and are omitted for consistency with other Google style guides.)
161+
162+
## Organization
163+
164+
### General Layout and Ordering
165+
166+
1.Copyright statement comment
167+
2.Author comment
168+
3.File description comment, including purpose of program, inputs, and outputs
169+
4.source() and library() statements
170+
5.Function definitions
171+
6.Executed statements, if applicable (e.g., print, plot)
172+
173+
Unit tests should go in a separate file named "originalfilename_test.R".
174+
175+
### Commenting Guidelines
176+
177+
Comment your code. Entire commented lines should begin with "#" and one space.
178+
179+
Short comments can be placed after code preceded by two spaces, "#", and then one space.
180+
```
181+
\# Create histogram of frequency of campaigns by pct budget spent.
182+
hist(df$pct.spent,
183+
breaks = "scott", # method for choosing number of buckets
184+
main = "Histogram: fraction budget spent by campaignid",
185+
xlab = "Fraction of budget spent",
186+
ylab = "Frequency (count of campaignids)")
187+
```
188+
### Function Definitions and Calls
189+
190+
Function definitions should first list arguments without default values, followed by those with default values.
191+
192+
In both function definitions and function calls, multiple arguments per line are allowed; line breaks are only allowed between assignments.
193+
**GOOD:**
194+
```
195+
PredictCTR <- function(query, property, numDays,
196+
showPlot = TRUE)
197+
```
198+
**BAD:**
199+
```
200+
PredictCTR <- function(query, property, numDays, showPlot =
201+
TRUE)
202+
```
203+
Ideally, unit tests should serve as sample function calls (for shared library routines).
204+
205+
### Function Documentation
206+
207+
Functions should contain a comments section immediately below the function definition line. These comments should consist of a one-sentence description of the function; a list of the function's arguments, denoted by Args:, with a description of each (including the data type); and a description of the return value, denoted by Returns:. The comments should be descriptive enough that a caller can use the function without reading any of the function's code.
208+
209+
Example Function
210+
211+
```
212+
CalculateSampleCovariance <- function(x, y, verbose = TRUE) {
213+
# Computes the sample covariance between two vectors.
214+
#
215+
# Args:
216+
# x: One of two vectors whose sample covariance is to be calculated.
217+
# y: The other vector. x and y must have the same length, greater than one,
218+
# with no missing values.
219+
# verbose: If TRUE, prints sample covariance; if not, not. Default is TRUE.
220+
#
221+
# Returns:
222+
# The sample covariance between x and y.
223+
n <- length(x)
224+
# Error handling
225+
if (n <= 1 || n != length(y)) {
226+
stop("Arguments x and y have different lengths: ",
227+
length(x), " and ", length(y), ".")
228+
}
229+
if (TRUE %in% is.na(x) || TRUE %in% is.na(y)) {
230+
stop(" Arguments x and y must not have missing values.")
231+
}
232+
covariance <- var(x, y)
233+
if (verbose)
234+
cat("Covariance = ", round(covariance, 4), ".\n", sep = "")
235+
return(covariance)
236+
}
237+
```
238+
239+
### TODO Style
240+
241+
Use a consistent style for TODOs throughout your code.
242+
```
243+
TODO(username): Explicit description of action to be taken
244+
```
245+
### Attach
246+
247+
The possibilities for creating errors when using "attach" are numerous. Avoid it.
248+
249+
### Functions
250+
251+
Errors should be raised using stop().
252+
253+
### Objects and Methods
254+
255+
The S language has two object systems, S3 and S4, both of which are available in R. S3 methods are more interactive and flexible, whereas S4 methods are more formal and rigorous. (For an illustration of the two systems, see Thomas Lumley's "Programmer's Niche: A Simple Class, in S3 and S4" in R News 4/1, 2004, pgs. 33 - 36: http://cran.r-project.org/doc/Rnews/Rnews_2004-1.pdf.)
256+
257+
Use S3 objects and methods unless there is a strong reason to use S4 objects or methods. A primary justification for an S4 object would be to use objects directly in C++ code. A primary justification for an S4 generic/method would be to dispatch on two arguments.
258+
259+
Avoid mixing S3 and S4: S4 methods ignore S3 inheritance and vice-versa.

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /