Non standard evalution
library(pkg_name)
uses non standard evaluation (NSE) when evaluating the name of the package to to be loaded. This is why pkg_name
needs not be quoted with apostrophes or single quotes.
While NSE safes two characters, it is a constant source of confusion when a package is attempted to be loaded whose name is stored in a variable. The following snippet causes the error Error in library(pkg) : there is no package called ‘pkg’. Execution halted
packages_to_load <- c('ggplot2', 'sqldf');
for (pkg in packages_to_load) {
print(paste('Trying to load', pkg));
library(pkg);
}
In order to specify the package to be loaded with a variable, the character.only
argument needs to be set to TRUE
:
packages_to_load <- c('ggplot2', 'sqldf');
for (pkg in packages_to_load) {
print(paste('Trying to load', pkg));
library(pkg, character.only = TRUE);
}
It is also possible to load a package from a variable with a combination of
eval
and
bquote
:
packages_to_load <- c('ggplot2', 'sqldf');
for (pkg in packages_to_load) {
print(paste('Trying to load', pkg));
eval(bquote(library(.(pkg))));
}
#
# Show loaded packages
#
(.packages());
packages_to_load <- c('ggplot2', 'sqldf');
for (pkg in packages_to_load) {
print(paste('Trying to load', pkg));
do.call('library', list(package = as.name(pkg)));
}