Other Recommendations
In this lesson, we have added a few recommendation for using the R language.
R Language recommendations
- Use
library()
instead ofrequire()
, unless it is a conscious choice. Package names should be characters (avoid NSE – non-standard evaluation).
# Goodlibrary("dplyr")# Badrequire(dplyr)
- In a function call, arguments can be specified by position, complete name, or partial name. Never specify by partial name and never mix by position and complete name.
# GOODmean(x, na.rm = TRUE)rnorm(10, 0.2, 0.3)# BADmean(x, na = TRUE)rnorm(mean = 0.2, 10, 0.3)
-
While developing a package, specify arguments by name.
-
The required (with no default value) arguments should be first, followed by optional arguments.
# GOODraise_to_power(x, power = 2.7)# BADraise_to_power(power = 2.7, x)
- The
...
argument should either be in the beginning or the end.
# GOODstandardize(..., scale = TRUE, center = TRUE)save_chart(chart, file, width, height, ...)# BADstandardize(scale = TRUE, ..., center = TRUE)save_chart(chart, ..., file, width, height)
- Good practice rule is to set default arguments inside the function using
NULL
idiom, and avoid dependence between arguments:
# GOODhistogram <- function(x, bins = NULL) {if (is.null(bins)) bins <- nclass.Sturges(x)...}# BADhistogram <- function(x, bins = nclass.Sturges(x)) {...}
-
Always validate arguments in a function.
-
While developing a package, specify the namespace of each used function, except if it is from a base package.
-
Do NOT put more than one statement (command) per line. Do NOT use a semicolon
;
as a termination of the command.
# GOODx <- 1x <- x + 1# BADx <- 1; x <- x + 1
-
Avoid using
setwd("/Users/irudnyts/path/that/only/I/have")
. Almost surely your collaborators will have different paths, which makes the project not portable. Instead, usehere::here()
function fromhere()
package. -
Avoid using
rm(list = ls())
. This statement deletes all objects from the global environment and gives you an illusion of a fresh R start.
Remember
- Use common sense and BE CONSISTENT.
- If you are editing code, take a few minutes to look at the code around you and determine its style.
- The point of having style guidelines is to have a common vocabulary.