Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are we able to generate a list of loaded packages in R?

Is there a function where we can generate a list of required packages in R? Something similar to "pip freeze" so we can duplicate environments quickly?

like image 805
Max Avatar asked May 03 '14 00:05

Max


2 Answers

Thanks for not being vague. Since you mentioned duplicating environments, here's some info about availability and namespaces of those available packages.

In addition to those functions mentioned by @smci, .Packages will list all packages available in the library location path lib.loc. And find.package will show you the path to the package. Bear in mind that find.packages can present issues when determining availability of a package. require is the recommended method (see ?find.package for explanation).

> x <- .packages(TRUE)
> head(x)
# [1] "assertthat"      "BH"              "car"             "data.table"     
# [5] "digest"          "dplyr"
> f <- find.package(x)
> sample(f, 5)
# [1] "/home/richard/R/x86_64-pc-linux-gnu-library/3.1/latticeExtra"  
# [2] "/home/richard/R/x86_64-pc-linux-gnu-library/3.1/Lahman"        
# [3] "/home/richard/R/x86_64-pc-linux-gnu-library/3.1/microbenchmark"
# [4] "/usr/lib/R/library/tools"                                      
# [5] "/home/richard/R/x86_64-pc-linux-gnu-library/3.1/knitr" 

For a list of the environments with namespaces for those packages in x, you can use (among others) getNamespace

> sapply(x, getNamespace)[1:3]
# $assertthat
# <environment: namespace:assertthat>

# $BH
# <environment: namespace:BH>

# $car
# <environment: namespace:car>
like image 143
Rich Scriven Avatar answered Nov 18 '22 11:11

Rich Scriven


If you meant "after running the code in question":

  • loadedNamespaces() (for just the package names, or)
  • search() as @Richard Scriven said

but if you meant statically analyze the code in question without running it, there's no tool I'm aware of, but mungeing the output of egrep -R -w '(require|include|source)' *.r should give you what you want (obviously will also pick up packages included but not used, or commented out)

like image 24
smci Avatar answered Nov 18 '22 11:11

smci