how to load a library dynamically? [duplicate] - r

This question already has answers here:
Load R package from character string
(2 answers)
Closed 7 years ago.
Sorry for asking easy question. I am a R beginner. I tried to load a library run-time,
e.g.
x<-"snow"; library(eval(x))
Result:
Error in library(eval(x)) : 'package' must be of length 1.
I would appreciate it if anyone gave me some solutions.

Use character.only=TRUE. See the help page for library, with ?library.
> library(x, character.only=TRUE)

I'd recommend to use require instead of library.
require returns a logical indicating whether the package was successfully loaded, i.e. you can use it in constructs like
if (require (x, character.only = TRUE))
...
On contrast, library will by default stop with an error if the package is not available (you can change this behaviour by logical.return = TRUE, though).
In case the package is loaded already, and this part of code is executed often, speed may matter: require is almost 20x faster than library on my laptop if the package is loaded already. If not, it calls library.

Related

Check if package is installed without loading [duplicate]

This question already has answers here:
Elegant way to check for missing packages and install them?
(33 answers)
Closed 4 years ago.
The typical way a package developer is advised to check whether a user has installed a package is like this:
if (!requireNamespace("package")) {
stop("Please install package.")
}
requireNamespace loads the package (in the current scope?) and returns a TRUE/FALSE value. I need to check the install state of a package without loading the namespace.
The reason for this is because I am writing a knit_print S3 method (extending the knitr package) and the namespace I am checking for kableExtra has side effects outside of the context of my knit_print method that I want to avoid.
When loaded, kableExtra changes how subsequent calls to knitr::kable are formatted at the global level. It has good reasons for doing so, but I want to use kableExtra inside my S3 method and not have end users confused about why kable behaves differently after my knit_print method is called.
That's why I want to do the check for the namespace (and if kableExtra is not installed, just call knitr::normal_print) without loading the namespace.
Edit: To clarify why I don't think this is a duplicate of this question, those answers do not pay any special attention to whether the solution loads the package when it is installed. It turns out that some of the solutions do not load the package in question, but they are not clearly differentiated.
Use installed.packages.
if ("kableExtra" %in% rownames(installed.packages()) {
# do something
}

How to make if statement to check whether a R package is installed or not in R [duplicate]

This question already has answers here:
Check for installed packages before running install.packages() [duplicate]
(16 answers)
Closed 6 years ago.
I am trying to make a personal R-function.
I want add if statement which can check whether essential R packages are installed.
I used exist() function but its purpose is to examine existence of an object
so it didn't work.
Is there a basic command for checking existence of a specific R-package in R?
Thx
You are looking for installed.packages() That will list all installed packages. Another option is require(thepackage) which will either load the package or return FALSE if the 'thepackage' is not available.
A way to do specifically what you asked is
"Package-Name" %in% installed.packages()
which will return TRUE or FALSE depending on whether or not "Package-Name" is installed.
However, if you're writing a script, you will usually want to use
library(Package-Name) or require(Package-Name)
If the package is installed, both will load it. If it isn't, library will throw an error, require will return FALSE and give a warning.

R warning: " 'package:stats' may not be available when loading"

I've been working with the arules package and RODBC package for a few days now in RStudio. I saved the workspace image multiple times in the meantime. But today I wanted to save my workspace image again and now I get this warning:
Warning message:
In save(list = ls(envir = .GlobalEnv, all.names = TRUE), file = outfile, :
'package:stats' may not be available when loading
I only used arules and RODBC functions and str_split_fixed from stringr and some standard stuff like data.frame.
I didn't even use the stats package at all. When reloading the workspace image, it doesn't seem affected by it. But the warning is bothering me anyway, especially since stats is supposed to be a standard package of R, how can it be unavailable... How can I resolve this warning?
As the commentator didn't post his comment as an answer, I will close this question myself: it's a bug in RStudio and knowing this thanks to SO I could close down RStudio and a couple R programming sessions later the warning message did not occur again.
This is now an official rstudio bug.
In my case (the repro in the bug) the root cause was that one of the objects I was trying to save referenced an rstudio-internal function (this isn’t very exotic. A plain options call returns a list that does that). RStudio functions live in tools:rstudio namespace, which inherits the stats package among others - hence the warning.
It is currently planned to be fixed as part of v1.4.

On-demand installation of packages [duplicate]

This question already has answers here:
Elegant way to check for missing packages and install them?
(33 answers)
Closed 9 years ago.
Is there a "standard" way to load a package, and install it if it isn't installed yet? Something like
if (!is.installed(package))
install(package)
library(package)
(pseudocode!), encapsulated in a neat function?
I'm usually having a hard time after wiping my private site library, which I do every now and then. If my scripts all used this "install-on-demand" facility, this would just happen automatically.
Dason K. and I have a package in the works on GitHub that needs some testing and a bit of cleaning and eventually will be pushed to CRAN. The function p_load in the package does this.
library(devtools)
install_github("trinker/pacman")
I see that other answers have been given but my preference would be:
if ( !require('pkg') ) { install.packages('pkg', dependencies=TRUE);
require('pkg') }
If you want to suppress the warning, then add quietly=TRUE to the first require call. I suppose you could bundle this into a function, called, what? insist?
insist <- function(pkg){
if ( !require(pkg, character.only=TRUE) ) {
install.packages(as.character(pkg), dependencies=TRUE)
require(pkg, character.only=TRUE) }
}
(My major stumbling block: The first argument to require didn't seem to get evaluated unless character.only=TRUE. Took me several reads of the ?require page to get this idea. Just slow, I guess.)

How to avoid printing a package's author message? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Library/package development - message when loading
I want to set up a web interface using Rapache; however, the underlying R code uses packages that display a quick message from the author. E.g., for data.table,
Quick start guide : vignette("datatable-intro") Homepage : http://datatable.r-forge.r-project.org/
Is there a way to avoid this? I tried suppressMessages(), and the quietly option to library(), but to no avail.
Thanks
For data.table, this was done in commit 233 (2011.06.11 01:04:27) :
"onAttach now uses packageStartupMessage so the banner can be suppressed by those annoyed by banners, whilst still being helpful to new users"
This is in v1.6.1 available from R-Forge, and may be released to CRAN soon.
I'll add a note to NEWS ...
The brute force way of suppressing all output and messages for chatty packages is to use sink:
t <- tempfile()
tcon <- file(t,open="w+")
sink(file=tcon,type='output')
sink(file=tcon,type='message')
require(YOURLIBRARY)
sink(NULL,type='output')
sink(NULL,type='message')
unlink(t)
TAKE THAT YOU CHATTY PACKAGE!

Resources