Image from Hackernoon
This is a summary of good habits to get into when coding in general. Since I use R, these will be related to R code. It is derived from the book “Good habits for great coding” by Michael Stueben available here.
## Author: Simon Thornley
## 23/09/2022
## Program to analyse New Zealand all-cause mortality data
## for the time-point most likely to result in a step-change.
## The data is available from here:
## ("https://mortality.org/File/GetDocument/Public/STMF/Outputs/stmf.csv")
For example:
## Function to truncate number to two decimal places
## Returns character of input number to two decimal places.
<- function(x){
trunc_two_d_p_number stopifnot("`x` must be numeric." = is.numeric(x))
formatC(x, digits = 2, format = "f")
}
Label and align your output
Avoid global variables, but global constants are ok.
In the body of your program, try to limit it to calls to other functions.
Write self-documenting code. This includes ‘verb-object’ function names and descriptive names of variables or data frames.
Refactor your code to make it more streamlined.
Prefer simpler over clever code.
Use a consistent style, such as Google’s R style guide.
If you don’t understand what your code is doing, use that as a prompt to do some research.
For example:
## Function to truncate number to two decimal places
## Returns character
<- function(x){
trunc_two_d_p_number stopifnot("`x` must be numeric." = is.numeric(x))
formatC(x, digits = 2, format = "f")
}
## Correct input
trunc_two_d_p_number(3.1415926)
## [1] "3.14"
## Incorrect input
trunc_two_d_p_number("four")
## Error in trunc_two_d_p_number("four"): `x` must be numeric.
## Alternative
<- function(x){
trunc_two_d_p_number if (!is.numeric(x))
stop("argument should be numeric")
formatC(x, digits = 2, format = "f")
}
## Global variable to error check
<- TRUE
Error_check
## Function to truncate number to two decimal places and returns character
<- function(x){
trunc_two_d_p_number stopifnot("`x` must be numeric." = is.numeric(x))
formatC(x, digits = 2, format = "f")
}
## Check output is as expected...
if (Error_check){
if (trunc_two_d_p_number(3.14159) == "3.14") {
print("Error check passed")
else print("Error check failed")
} }
## [1] "Error check passed"
## boundary test
trunc_two_d_p_number(1e+50) |> print()
## [1] "100000000000000007634202480888288842446682800440060.00"
## Incorrect input
trunc_two_d_p_number("four")
## Error in trunc_two_d_p_number("four"): `x` must be numeric.