Ideas for what to do with packages?


I was wondering what people do with their packages? At the moment, I have a markdown document, and an entire chunk called 'packages'.

A small part of it looks like the below (as an example)

options(repos="" )
if (!require("ggstatsplot")) install.packages("ggstatsplot")

if (!require("Hmisc")) install.packages("Hmisc")

Each time I knit, all the packages are installed, and loaded. I guess my questions are:

  1. Does markdown have to install + load all packages each time? This takes a while
  2. Is there a way to check which I've used? I'm sure I have more packages in the chunk than I need, but other than deleting each individually and seeing if it affects my analysis, I'm not sure what to do.
  3. I was trying to use bookdown, but I had some trouble with it (will use when I don't have a deadline)! I don't really understand how packages work in bookdown, is it best to put them all in index, and none in subsequent chapters? I've also seen some save them as .bib files in there (though maybe this is just the reference to the package, rather than a list of all the packages).

Thanks for your help

This is the answer only to your first question. You can avoid installing all the packages every time you knit the document by conditionally checking which packages are not currently installed and only installing those.

# needed packages
pkgs <- c( "ggstatsplot", "tidyverse")

# check if there are any missing
missing_pkgs <- pkgs[!(pkgs %in% installed.packages()[, "Package"])]

# install missing ones
if (length(missing_pkgs) > 0) {

# load 'em up
library(tidyverse, warn.conflicts = FALSE)

But this does require keeping track of all packages you are using and keep updating the pkgs vector with every new package you use in the script.

1 Like

Wonderful, this works well for my first question-thank you so much!!

I only want to point out that if you (an your team) are using RStudio, there is no need to include code for installing missing packages, you just have to load them in your Rmd file, RStudio has a built-in functionality that will offer you to install any missing package when you open your Rmd file, and it installs them on a background job.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.