rnamespacespackageloadedsearch-path

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?


Solution

  • 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>