9 Software development concepts
9.1 Good coding practices
9.1.1 Script structure
- Use comments to create sections.
- Load all required packages at the very beginning.
- Write all function definitions after package loading section or create a standalone file for your functions and call it in the main code.
9.1.2 Functions
Identify functions capitalizing the first letter of each word
# Good
DoNothing <- function() {
return(invisible(NULL))
}
# Bad
donothing <- function() {
return(invisible(NULL))
}
Use explicit returns
Define what the functions does, the input parameters, and output using comments inside the function
AddValues <- function(x, y) {
# Description: Function to add to numeric variables
# Input
# x = numeric
# y = numeric
# Output: numeric
return(x + y)
}
Testing and documenting
- Use formal documentation for functions whenever you are writing more complicated projects. This documentation is written in separate
.Rd
files,and it turns into the documentation printed in the help files. - The
roxygen2
package allows R coders to write documentation alongside the function code and then process it into the appropriate.Rd
files. - Formal automated tests can be written using the
testthat
package.
9.1.3 External packages
Packages are essentially bundles of functions with formal documentation. Loading your own functions through
source("functions.R")
is similar to loading someone else’s usinglibrary("package")
As a general rule, only load a package using
library()
if you are going to use more than two functions from if.Use the name space when calling an external function. Not doing it can cause clashes when two packages have a function with the same name.