Getting started: check and correct a function
Each checking function prints a table-like message of the problematic
lines and returns the corrected function (or NULL if
nothing has to be corrected). With export = TRUE, the
corrected function is written into a
<function name>_safer.R file instead. Exception:
super_assign_check() returns an error if any
<<- or ->> is detected, because
what these operators modify cannot be guessed from the code.
Recommended order: super_assign_check() (error only,
nothing corrected automatically), lambda_check(),
colons_check() and all_args_here() (these two
require the previous steps), then curly_bracket_check(),
true_false_check() and
for_loop_nb_check().
library(saferDev)
# function with missing package attributions, missing arguments, missing curly brackets,
# an abbreviated logical value and a for() sequence not written with hard numbers
fun1 <- function(x, y = T){
if(x > 1) z <- mean(x)
for(i in 1:length(y)){
z <- base::paste0(z, i)
}
z
}
fun2 <- colons_check(x = fun1) # base:: added before mean() and length()
##
##
## INSIDE fun1(), SOME :: OR ::: ARE MISSING BEFORE BASIC FUNCTIONS:
##
## LINE FUN STRING_BEFORE
## 4 mean z <-
## 5 length for (i in 1:
fun3 <- all_args_here(x = fun2) # missing arguments added
##
## INSIDE fun2(), ARGUMENTS ARE MISSING.
## LINE_NB FUN_NAME FUN_ARGS FUN_POS DEF_ARGS
## 1 4 mean mean(x) 12 x, ...
## 2 5 length length(y) 19 x
## 3 6 paste0 paste0(z, i) 12 ..., collapse = NULL, recycle0 = FALSE
## MISSING_ARG_NAMES MISSING_ARGS
## 1 x x = x
## 2 x x = y
## 3 collapse, recycle0 collapse = NULL, recycle0 = FALSE
## STATUS
## 1 mean(x = x)
## 2 length(x = y)
## 3 paste0(z, i, collapse = NULL, recycle0 = FALSE)
fun4 <- curly_bracket_check(x = fun3) # { } added after if()
##
##
##
## INSIDE fun3(), SOME CURLY BRACKETS {} ARE MISSING AFTER:
##
## LINE CONSTRUCT CODE
## 3 if if (x > 1)
fun5 <- true_false_check(x = fun4) # T replaced by TRUE
##
##
##
## INSIDE fun4(), SOME SYMBOLS T OR F MUST BE WRITTEN TRUE OR FALSE:
##
## LINE SYMBOL CODE
## 1 T function (x, y = T)
## function (x, y = TRUE)
## {
## if (x > 1)
## { z <- base::mean(x = x) }
## for (i in 1:base::length(x = y)) {
## z <- base::paste0(z, i, collapse = NULL, recycle0 = FALSE)
## }
## z
## }
## <environment: 0x62f3aafdf928>
fun6 <- for_loop_nb_check(x = fun5) # checking line added before the for() loop
##
##
##
## INSIDE fun5(), SOME for() SEQUENCES ARE NOT WRITTEN WITH HARD NUMBERS:
##
## LINE CONSTRUCT CODE
## 5 for for (i in 1:base::length(x = y)) {
fun6(x = 2, y = NULL) # 1:length(NULL) is c(1, 0): a warning is now returned
## Warning: FOR SEQUENCE DECREASING
## [1] "210"
See the website for
one article with more examples per function.