at the beginning of my R code I want to check if I have a package installed within a list of packages, if not, then install the package then load it. My code looks like this:
packages <- c("dplyr", "ggplot2")
for (p in packages)
{
if (library(p, logical.return= TRUE) == TRUE)
{
lapply(p, library, character.only = TRUE)
} else
{
install.packages(p)
lapply(p, library, character.only = TRUE)
}
}
I can see in the terminal that everytime I run this cell (btw I'm using jupyterlab with R kernel), I know that these packages are already installed but I can see in my terminal that it will install these pacakges again so there is a obvious flaw here, just not obvious what the flaw is. I am new to R so is there a better way of going about doing this?
Thank you
Your Code fails, because you don't use character.only
in the if
condition, so your library
statement tries to find a package named p
. A solution with require
instead of library
(require already returns TRUE or FALSE, depending on the install status), which is a bit cleaned up compared to your code:
packages <- c("dplyr","ggplot2")
for(p in packages)
{
tryCatch(test <- require(p,character.only=T),
warning=function(w) return())
if(!test)
{
print(paste("Package", p, "not found. Installing Package!"))
install.packages(p)
require(p)
}
}
Be aware that this will always attach the namespaces of the packages to check. So if you just want to install missing packages, without loading them, the solution mentioned in the comment under your question works better.
One way you could achieve this is by checking if it is installed using the installed.packages()
function. Then, you can also check which packages are loaded by using the .packages()
function.
When you implement this, it'd look like this:
# Declare packages
packages <- c("dplyr","ggplot2","magrittr")
# Loop through each package
for (package in packages) {
# Install package
# Note: `installed.packages()` returns a vector of all the installed packages
if (!package in installed.packages()) {
# Install it
install.packages(
package,
dependencies = TRUE
)
}
# Load package
# Note: `.packages()` returns a vector of all the loaded packages
if (!package in .packages()) {
# Load it
library(
package,
character.only = TRUE
)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.