forked from tidyverse/style
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path03-functions.Rmd
executable file
·92 lines (71 loc) · 2.23 KB
/
03-functions.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# Functions
## Naming
Use verbs for function names, where possible.
```{r eval = FALSE}
# Good
add_row()
permute()
# Bad
row_adder()
permutation()
```
## Long lines
If a function definition runs over multiple lines, indent the second line to
where the definition starts.
```{r, eval = FALSE}
# Good
long_function_name <- function(a = "a long argument",
b = "another argument",
c = "another long argument") {
# As usual code is indented by two spaces.
}
# Bad
long_function_name <- function(a = "a long argument",
b = "another argument",
c = "another long argument") {
# Here it's hard to spot where the definition ends and the
# code begins
}
```
## `return()`
Only use `return()` for early returns. Otherwise rely on R to return the result
of the last evaluated expression.
```{r eval = FALSE}
# Good
find_abs <- function(x, y) {
if (x > 0) return(x)
x * -1
}
add_two <- function(x, y) {
x + y
}
# Bad
add_two <- function(x, y) {
return(x + y)
}
```
If your function is called primarily for its side-effects (like printing,
plotting, or saving to disk), it should return the first argument invisibly.
This makes it possible to use the function as part of a pipe. `print` methods
should usually do this, like this example from httr:
```{r eval = FALSE}
print.url <- function(x, ...) {
cat("Url: ", build_url(x), "\n", sep = "")
invisible(x)
}
```
## Comments
In code, use comments to explain the "why" not the "what" or "how". Each line
of a comment should begin with the comment symbol and a single space: `# `.
## Design
There are two main design principles to bear in mind:
* A function should do one thing well.
A function should be called either because it has side-effects or
because it returns a value; not both. Strive to keep blocks within
a function on one screen. 20-30 lines per function are common. For
functions that are significantly longer, consider splitting it into smaller
functions.
* A function should be easily understandable in isolation.
Avoid global options. If your function has a transient side-effect
(i.e. you need to create a temporary file or set an option), clean up
after yourself with `on.exit()`.