How to (correctly) load a package

The great Fela sang “Teacher no teach me nonsense“.

While taking a course in Machine Learning the other day, I came across this:

set.day.of.week <- function() {
library(dplyr)

## First day of the dataset is Saturday
data.frame(weekdays = c(0, 1, 2, 3, 4, 5, 6),
daysOfWeek = c("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"),
stringsAsFactors = FALSE)
}

To find this kind of code on a course amazed even me, an R neophyte, as there is so much with this function that is wrong and it really left me puzzled. What made it worse was that the course is being organised by a reputable software giant.

But please, if you're loading (or more correctly, attaching) a package within a function, do not call library(); rather make use of require(). This blog by the author of the knitr package explains it better than I ever could.

UPDATE (18 December 2017)
I learnt something new. If you don’t really need to attach a package, say when there’s only a single function call to be done, one can just use requireNamespace() . This is very useful, for example, when you’re sharing a script and you want to add a check to ensure that the user has the right package installed…


if (!requireNamespace(devtools)
  install.packages("devtools")
devtools::install_github("BroVic/smexplorer")

This code will check whether the package devtools is in the local library, and if not, immediately download it from the Comprehensive R Archive Network (CRAN) and install it. Then a function from the package is called to install another package from GitHub.

One thought on “How to (correctly) load a package

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