What a “freak” occurrence taught me about installing R packages

I was trying to set up a particular Rmarkdown document in such a way that other users on our team, who might not have all the necessary packages installed, could get them automatically.

pkglist <- c("dplyr",
             "ggplot2",
             "lubridate",
             "qdap",
             "stringr",
             "tm",
             "twitteR",
             "wordcloud")

# Extract names of any missing packages
not_installed <- pkglist[!pkglist %in% installed.packages()[, "Package"]]

install.packages(not_installed)

# Load all the packages
lapply(pkglist, library, character.only = TRUE)

The first time I tried it out it worked perfectly, but later when I re-knitted the document, this funny window popped up

R package list

I was quite surprised! Oh, what had I done now?

To cut the story short, the answer lies in the R documentation via help('install.packages'):

part documentation for R function

So, argument pkgs (3rd paragraph), when zero-length, is what produced the popup. After installing the missing packages in the first pass of the code I wrote, the vector not_installed was subsequently zero-length. As an example, when one does this…

install.packages(character())

…our listbox appears.

I therefore decided to throw in a conditional statement to skip the installation step in the event that all required packages are already present:

pkglist <- c("dplyr",
             "ggplot2",
             "lubridate",
             "qdap",
             "stringr",
             "tm",
             "twitteR",
             "wordcloud")
not_installed <- pkglist[!pkglist %in% installed.packages()[, "Package"]]

# In case none of the listed packages are missing
if (length(not_installed))
  install.packages(not_installed)

lapply(pkglist, library, character.only = TRUE)

Done.

One thought on “What a “freak” occurrence taught me about installing R packages

Comments

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s