...

/

Other Recommendations

Other Recommendations

In this lesson, we have added a few recommendation for using the R language.

R Language recommendations

  1. Use library() instead of require(), unless it is a conscious choice. Package names should be characters (avoid NSE – non-standard evaluation).
Press + to interact
# Good
library("dplyr")
# Bad
require(dplyr)
  1. 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.
Press + to interact
# GOOD
mean(x, na.rm = TRUE)
rnorm(10, 0.2, 0.3)
# BAD
mean(x, na = TRUE)
rnorm(mean = 0.2, 10, 0.3)
  1. While developing a package, specify arguments by name.

  2. The required (with no default value) arguments should be first, followed by optional arguments.

Press + to interact
# GOOD
raise_to_power(x, power = 2.7)
# BAD
raise_to_power(power = 2.7, x)
  1. The ... argument should either be in the beginning or the end.
Press + to interact
# GOOD
standardize(..., scale = TRUE, center = TRUE)
save_chart(chart, file, width, height, ...)
# BAD
standardize(scale = TRUE, ..., center = TRUE)
save_chart(chart, ..., file, width, height)
  1. Good practice rule is to set default arguments inside the function using NULL idiom, and avoid dependence between arguments:
Press + to interact
# GOOD
histogram <- function(x, bins = NULL) {
if (is.null(bins)) bins <- nclass.Sturges(x)
...
}
# BAD
histogram <- function(x, bins = nclass.Sturges(x)) {
...
}
  1. Always validate arguments in a function.

  2. While developing a package, specify the namespace of each used function, except if it is from a base package.

  3. Do NOT put more than one statement (command) per line. Do NOT use a semicolon ; as a termination of the command.

Press + to interact
# GOOD
x <- 1
x <- x + 1
# BAD
x <- 1; x <- x + 1
  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, use here::here() function from here() package.

  2. 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.