3 Functions
3.1 Naming
As well as following the general advice for object names, strive to use verbs for function names:
# Good
add_row()
permute()
# Bad
row_adder()
permutation()
3.2 Long lines
If a function definition runs over multiple lines, indent the second line to where the definition starts.
# Good
function(a = "a long argument",
long_function_name <-b = "another argument",
c = "another long argument") {
# As usual code is indented by two spaces.
}
# Bad
function(a = "a long argument",
long_function_name <-b = "another argument",
c = "another long argument") {
# Here it's hard to spot where the definition ends and the
# code begins
}
3.3 return()
Only use return()
for early returns. Otherwise, rely on R to return the result
of the last evaluated expression.
# Good
function(x) {
find_abs <-if (x > 0) {
return(x)
}* -1
x
} function(x, y) {
add_two <-+ y
x
}
# Bad
function(x, y) {
add_two <-return(x + y)
}
Return statements should always be on their own line because they have important effects on the control flow. See also inline statements.
# Good
function(x) {
find_abs <-if (x > 0) {
return(x)
}* -1
x
}
# Bad
function(x) {
find_abs <-if (x > 0) return(x)
* -1
x }
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:
function(x, ...) {
print.url <-cat("Url: ", build_url(x), "\n", sep = "")
invisible(x)
}
3.4 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:
#
.Comments should be in sentence case, and only end with a full stop if they contain at least two sentences: