10

Is there any way to "check" or "verify" a source code file in R when sourcing it ? For example, I have this function in a file "source.R"

MyFunction <- function(x)
{
print(x+y)
}

When sourcing "source.R", I would like to see some sort of warning : MyFunctions refers to an undefined object Y.

Any hints on how to check / verifiy R code ?

Cheers!

Tarod
  • 6,732
  • 5
  • 44
  • 50
MadSeb
  • 7,958
  • 21
  • 80
  • 121

2 Answers2

10

I use a function like this one for scanning all the functions in a file:

critic <- function(file) {

   require(codetools)
   tmp.env <- new.env()
   sys.source(file, envir = tmp.env)
   checkUsageEnv(tmp.env, all = TRUE)

}

Assuming source.R contains the definitions of two rather poorly written functions:

MyFunction <- function(x) {
   print(x+y)
}

MyFunction2 <- function(x, z) {
   a <- 10
   x <- x + 1
   print(x)
}

Here is the output:

critic("source.R")
# MyFunction: no visible binding for global variable ‘y’
# MyFunction2: local variable ‘a’ assigned but may not be used
# MyFunction2: parameter ‘x’ changed by assignment
# MyFunction2: parameter ‘z’ may not be used
flodel
  • 87,577
  • 21
  • 185
  • 223
5

You can use the codetools package in base R for that. And if you had your code in a package, it would tell you about this:

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725