Best practices for location of library() in .Rmd files

Then, yes, of course that's what I meant! :stuck_out_tongue_winking_eye:

1 Like

Super, will check this out. Thanks everyone -- love this forum -- I am learning so much!

1 Like

I tend to use package managers for library load and management: pacman

https://cran.r-project.org/web/packages/pacman/vignettes/Introduction_to_pacman.html

With pacman::p_load() instead of 5 lines of code to load 5 common packages, like this:

library(dplyr)
library(tidyr)
library(Hmisc)
library(magrittr)
library(janitor)

You can write one line

pacman::p_load(dplyr, tidyr, Hmisc, janitor, magrittr)

if the package is not available on the system, it will first install it (through install.packages), and only then try to load it again. Same as library installr

installr::require2

All of this, on the very first part of any R file.

2 Likes

I'm generally a fan of pacman, particularly when I start using less common packages. That way, when I need to re-run my analysis down the road, it can automatically reinstall them since I've inevitably lost (or cleaned out) my packages since the last time I ran it. The "bootstrapping" script header provided by pacman::p_boot() is also convenient if you share scripts with people less familiar with R (or at least people that won't mind your script auto-installing some packages):

if (!require("pacman")) install.packages("pacman"); library(pacman)
3 Likes