Finding a Package

Sometimes you just want to know whether a package is installed on your computer. Well, today I just discovered a function find.package() that does just that. However, its return value is the path to the location where the package is installed on your system, which may not be all that useful when using it in the control of flow.

Another way of checking this (I’ve been using this before now) is with the %in% operator which returns a logical vector to indicate whether there is a match for the inputted value or not.

# Check whether package "base" is installed
"base" %in% installed.packages()[, 1]

[1] TRUE

I found this approach very useful when the presence or absence of a package is required to decide on a line of action. I found the code above to be some nasty typing so I made a custom function that accomplishes the same thing. It looks like this:

checkpkg <- function (pkg) {
# ...input validation would normally come here...
return(pkg %in% rownames(utils::installed.packages()))

Note that I used rownames() here instead of subsetting installed.packages() like I did in the other example. So, whenever I want to check for a package on my computer I just type checkpkg("package name").



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

You are commenting using your 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