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