8

For example, if ran the script.A:

 library(ggplot2)
 a <- 12 

and then script.B

library(ggplot2)
b <- runif(100)
qplot(b) 

I'd be able to tell that script.A did not actually make use of ggplot2, whereas script.B did.

John Horton
  • 4,122
  • 6
  • 31
  • 45
  • Do you need to know what package the functions came from? – Thomas Aug 18 '13 at 15:30
  • What I'd actually like to do is eliminate packages that are not being used. As I re-use code from old projects, I seem to always add (but never take-away) packages, and while I could manually do some kind of bisect to find the unused packages, this would be a hassle. Ideally, I could just get a post-execution run-down of what actually was called. – John Horton Aug 18 '13 at 15:34
  • 1
    Do any of these help: http://stackoverflow.com/questions/8761857/identifying-dependencies-of-r-functions-and-scripts and http://stackoverflow.com/questions/17402735/between-function-possible-improvement – Thomas Aug 18 '13 at 15:44

2 Answers2

5

Load the library normally and trace all functions in the package environment (and in the namespace). I'll use a small helper function to do this:

trap_funs <- function(env)
{
    f <- sapply(as.list(env, all.names=TRUE), is.function)
    for( n in names(f)[f] ) trace(n, bquote(stop(paste("Script called function", .(n)))), where=env)
}

Example:

library(data.table)
trap_funs(as.environment("package:data.table"))
trap_funs(asNamespace("data.table"))

This second statement is needed to ensure that calls such as data.table::xxx() also get trapped.

Example:

> as.data.table(mtcars)
Tracing as.data.table(mtcars) on entry 
Error in eval(expr, envir, enclos) : Script called function as.data.table

Note that the code was interrupted.

Ferdinand.kraft
  • 12,579
  • 10
  • 47
  • 69
0

Try this:

1) First issue a library() call for each package that you do NOT want to test for. In this case there is only one package which is the one we wish to test for so we can skip this step.

2) Run the script with library dummied out:

library <- list
source("script.A")
rm(library) # restore

If you get no errors then the script does not depend on the package.

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341