Search R file by used package

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

Is there any way to indicate which functions from this package were used in the particula file?

+4
source share
1 answer

Of course, there are other ways to do this, but if you can get a list of functions for the package, you can combine readLines(to read the script in R as characters), grepl(to determine matches) and sapply. The way I captured the functions uses p_funsfrom the pacman package . (Full disclosure: I am one of the authors).

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

library(ggplot2)

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

summary(x)

and here is the session in which I determine 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 do not want to install pacman, you can use any other method to get a list of functions in the package. You can replace this with

funs <- objects("package:ggplot2")

and you will get the same answer.

, , , - , ggplot script, "ggplot" library(ggplot2). , .

+5

Source: https://habr.com/ru/post/1537227/


All Articles