user1754606
user1754606

Reputation: 1379

Search R file by package used

Let's say I open R file that I used way back when. On top of the page I see a library loaded, but I don't remember what it does any more. So I think to myself: hm, I wonder where in this long R file is this library used?

Is there a way to list what functions from a given package were used in particula file?

Upvotes: 4

Views: 66

Answers (1)

Dason
Dason

Reputation: 61933

There are certainly other ways to do this but if you can get a list of the functions for the package you could combine readLines (to read the script into R as characters), grepl (to detect matches), and sapply. The way I would grab the functions is using p_funs from the pacman package. (Full disclosure: I am one of the authors).

Here is an example script that I have saved as "test.R"

library(ggplot2)

x <- rnorm(20)
y <- rnorm(20)
qplot(x, y)

summary(x)

and here is a session where I detect which functions are used

script <- readLines("test.R")
funs <- p_funs(ggplot2)
out <- sapply(funs, function(input){any(grepl(input, x = script))})
funs[out]
#[1] "ggplot" "qplot"

If you don't want to install pacman you can use any other method to get a list of the functions in the package. You could replace that with

funs <- objects("package:ggplot2")

and you would essentially get the same answer.

Note that you may get more matches than there actually are in the file - note that the ggplot function wasn't actually in my script but the string "ggplot" is in library(ggplot2). So you may still need to do a little bit of additional digging after the initial sweep through the file.

Upvotes: 5

Related Questions