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

筅森魡賤 提交于 2019-12-04 17:04:28

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>

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, 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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!