Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to tell if an R script made use of any function in a loaded package?

Tags:

r

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.

like image 895
John Horton Avatar asked Aug 18 '13 15:08

John Horton


1 Answers

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.

like image 138
Ferdinand.kraft Avatar answered Sep 19 '22 02:09

Ferdinand.kraft