Reputation: 2253
I have written a function to get the name and version of all of my loaded packages:
my_lib <- function(){
tmp <- (.packages())
tmp_base <- sessionInfo()$basePkgs
tmp <- setdiff(tmp, tmp_base)
tmp <- sort(tmp)
tmp <- sapply(tmp, function(x){
x <- paste(x, utils::packageVersion(x), sep = ' v')
})
tmp <- paste(tmp, collapse=', ')
return(tmp)
}
This also returns all packages loaded as dependencies to other packages (eg I load car
and carData
is loaded as a dependency).
I am wondering if there is a way to only return the packages I manually loaded (eg just car
)? Can R tell the difference between manually loaded vs loaded as a dependency?
Edit:
Added line to remove base packages using sessionInfo()
Upvotes: 1
Views: 853
Reputation: 5059
R has a subtle difference between a loaded package and an attached package.
A package is attached when you use the library
function,
and it makes its exported functions "visible" to the user's global environment.
If a package is attached,
its namespace has been loaded,
but the opposite is not necessarily true.
Each package can define two main types of dependencies: Depends
and Imports
.
The packages in the former get attached as soon as the dependent package is attached,
but the packages in the latter only get loaded.
This means you can't completely differentiate,
because you may call library
for a specific package,
but any packages it Depends
on will also be attached.
Nevertheless, you can differentiate between loaded and attached packages with loadedNamespaces()
and search()
.
EDIT: It just occurred to me that if you want to track usage of library
(ignoring require
),
you could write a custom tracker:
library_tracker <- with(new.env(), {
packages <- character()
function(flag) {
if (missing(flag)) {
packages <<- union(packages, as.character(substitute(package, parent.frame())))
}
packages
}
})
trace("library", library_tracker, print = FALSE)
library("dplyr")
library(data.table)
# retrieve packages loaded so far
library_tracker(TRUE)
[1] "dplyr" "data.table"
The flag
parameter is just used to distinguish between calls made by trace
,
which call the function without parameters,
and those made outside of it,
in order to easily retrieve packages loaded so far.
You could also use environment(library_tracker)$packages
.
Upvotes: 1