Applied Epi Community

Best way to load/install packages?

Hi everyone, what is the best way for me to install several R packages efficiently?

I have seen code that uses install.packages(), and I have also seen pacman::p_load(). What is the difference between these? And also, how is library() related to this?

The packages that I want to use are: janitor, dplyr, ggplot2, and survival.

Many thanks for any clarity and help!

I think pacman::p_load is better because it checks to see if the package is installed and then loads the package. install.packages() only installs the package. So if you use install.packages(), you also have to load the package with library(). pacman::p_load conveniently does both for you. It’s also helpful when sharing code with others since it will check to see whether all necessary packages are installed before loading them.

If you used base R, you have to install and load them individually.

install.packages(c("janitor", "dplyr", "ggplot2", "survival"))

So for the packages you listed, I would use

pacman::p_load(janitor, dplyr, ggplot2, survival)

Here’s the EpiRHandbook page on it for reference: