Advertisement
Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Install, Load, and Unload Packages in R

You install a package in R with the function — wait for it — install.packages(). Who could’ve guessed? So, to install the fortunes package, for example, you simply give the name of the package as a string to the install.packages() function.

The fortunes package contains a whole set of humorous and thought-provoking quotes from mailing lists and help sites. You install the package like this:

> install.packages('fortunes')

R may ask you to specify a CRAN mirror. Because everyone in the whole world has to access the same servers, CRAN is mirrored on more than 80 registered servers, often located at universities. Pick one that’s close to your location, and R will connect to that server to download the package files. In RStudio, you can set the mirror by choosing Tools→Options.

Next, R gives you some information on the installation of the package:

Installing package(s) into 'D:/R/library'(as 'lib' is unspecified)
....
opened URL
downloaded 165 Kb
package 'fortunes' successfully unpacked and MD5 sums checked
....

It tells you which directory (called a library) the package files are installed in, and it tells you whether the package was installed successfully. Granted, it does so in a rather technical way, but the word successfully tells you everything is okay.

After a while, you can end up with a collection of many packages. If R loaded all of them at the beginning of each session, that would take a lot of memory and time. So, before you can use a package, you have to load it into R by using the library() function.

You load the fortunes package like this:

> library(fortunes)

You don’t have to put single quotation marks around the package name when using library(), but it may be wise to do so.

Now you can use the functions from this package at the command line, like this:

> fortune("This is R")

The library is the directory where the packages are installed. Never, ever call a package a library. That’s a mortal sin in the R community. Take a look at the following, and never forget it again:

> fortune(161)

You can use the fortune() function without arguments to get a random selection of the fortunes available in the package. It’s a nice read.

If you want to unload a package, you’ll have to use some R magic. The detach() function will let you do this, but you have to specify that it’s a package you’re detaching, like this:

> detach(package:fortunes)
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win an iPad Mini. Enter to win now!