Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R verify source code

Tags:

r

verification

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!

like image 603
MadSeb Avatar asked Aug 19 '12 21:08

MadSeb


People also ask

Is it possible to inspect the source code of R?

Anyone can inspect the source code to see how R works. Because of this transparency, there is less chance for mistakes, and if you (or someone else) find some, you can report and fix bugs.

How do I view source code in R?

If you want to view the code built-in to the R interpreter, you will need to download/unpack the R sources; or you can view the sources online via the R Subversion repository or Winston Chang's github mirror.

How do I view functions in R?

The View() function in R invokes a spreadsheet-style data viewer on a matrix-like R object. To view all the contents of a defined object, use the View() function. Behind the scenes, the R calls utils::View() on the input and returns it invisibly.


2 Answers

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
like image 89
flodel Avatar answered Nov 11 '22 17:11

flodel


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:

like image 42
Dirk Eddelbuettel Avatar answered Nov 11 '22 17:11

Dirk Eddelbuettel