02Home & Garden · Updated
How to Load R Packages in R
Short answer
Use library() to load an installed R package
Install a package once, then load it in each new R session with library(package_name). You can also use require() for conditional loading, but library() is the clearest choice for most scripts.
Loading an R package makes its functions and other exported tools available in your current R session. This is different from installing a package: installation puts the package files on your computer, while loading attaches its functions for use. You generally install a package once, then load it whenever you start a fresh session.
What You’ll Need
- R installed on your computer, or access to an R environment such as RStudio or a hosted R notebook.
- The package installed in a library folder that your current R installation can access. Many commonly used packages are distributed through CRAN.
- The exact package name, which may differ from the function names it provides. For example,
ggplot2is a package name. - An internet connection if you still need to install the package from an online repository.
Step-by-Step
- Start an R session. Open R, RStudio, or another environment that runs R code. In RStudio, enter commands in the Console or put them in an R script. A new session usually starts without packages you loaded previously.
- Check whether the package is installed. Run
"ggplot2" %in% rownames(installed.packages()), replacingggplot2with the package you need. The result isTRUEif R can find an installed copy andFALSEif not. You can also try loading it and install it if R reports that the package is missing. - Install it if needed. For a CRAN package, run
install.packages("ggplot2"). Use the package’s actual name inside the quotes. Installation downloads files and may ask you to choose a CRAN mirror; select one that is reachable. This step is not needed every time you use the package. - Load the package. Run
library(ggplot2). The name insidelibrary()is normally written without quotation marks. If the command completes without an error, the package is available in the current session. - Use a function from it. Call an exported function by its name, using the arguments it requires. For example, after loading
ggplot2, you can useggplot()in a plotting command. Loading a package does not run its functions automatically; it only makes them available. - Repeat loading in future sessions. Add the
library()call near the top of a script that relies on the package. Run the script in a fresh session to confirm it loads everything it needs. Scripts should not assume that a package remains attached from an earlier interactive session.
For a package that is not on CRAN, follow its official installation instructions. It may come from another repository or source, and the correct installation command can differ. Once installed, its loading command is still commonly library(package_name), but confirm the package documentation if that fails.
Common Mistakes
- Confusing installation with loading:
install.packages()installs files; it does not attach the package for use in later commands. Runlibrary()in each session where you need it. - Using the wrong name: A package’s name is not always the same as the function you want. Check the package documentation or installation instructions for the exact spelling and capitalization.
- Putting quotes in the wrong place:
library(ggplot2)is standard syntax.library("ggplot2")also works, butlibrary(ggplot2)with an unmatched quote or misspelled name will fail. - Loading before installing: If the package is not installed, R cannot load it. Install it first, then run
library(). - Assuming packages are available everywhere: Packages are installed for an R library and may not be available to a different computer, user account, R version, or hosted environment.
- Ignoring function-name conflicts: Two attached packages can provide functions with the same name. R may warn that one function masks another; the function from the package loaded later may be used when you call that name without qualification.
Tips
- Put package-loading commands at the beginning of scripts, before code that uses those packages. This makes dependencies easier to spot and failures easier to diagnose.
- Use
package::function()to call a function from a specific package without attaching the whole package. For example,stats::filter()identifies the function fromstatsand avoids ambiguity. - Use
requireNamespace("ggplot2", quietly = TRUE)when code needs to check for a package without attaching it. This is often suitable inside reusable functions or package code. require(ggplot2)attempts to load a package and returnsTRUEorFALSE. For ordinary scripts,library(ggplot2)is often preferable because a missing package produces a clear error instead of allowing later code to continue unexpectedly.- Keep a record of the packages your script needs. For a small script, clear
library()calls are usually enough; a project with many dependencies may benefit from a package-management tool. - Restart R and run the script from the top when checking whether it is self-contained. This helps reveal packages or objects that were available only because of earlier commands in your workspace.
Troubleshooting
“There is no package called …” Install the named package with install.packages("package_name"), then retry library(package_name). Check for spelling mistakes and make sure installation completed in the same R environment you are using.
Installation fails or cannot reach a repository. Check your internet connection and the repository or mirror selection. A work or school network may restrict downloads; ask its support team about the approved repository or proxy settings. If installation reports a permissions problem, use a library folder you are allowed to write to rather than changing system permissions blindly.
The package was installed but still cannot be found. R may be using a different library folder or installation than the one where the package was installed. Run .libPaths() to see the library folders R searches, and find.package("package_name") to check whether it can locate the package. Confirm that you are using the intended R installation and account.
A function is still not found. Confirm that the package loaded successfully and that the function belongs to that package. Check its spelling and documentation; some functions are not exported for direct use. If names conflict, call the function explicitly as package_name::function_name().
There is a version or dependency error. Read the full error message for a required R version or another package that must be installed or updated. Use compatible versions from the package’s official instructions. Restart R after updating packages, then try loading the package again.
Frequently Asked Questions
What is the difference between installing and loading an R package?
Installing saves the package files in an R library on your computer. Loading attaches the package’s exported functions to the current R session so you can use them.
Do I need to load a package every time I open R?
Usually, yes. A package must be loaded again in each new session unless your environment has been specially configured to load it automatically. Scripts should include their own required library() calls.
Can I load several packages at once?
Run a separate library(package_name) command for each package. Keeping one package per line makes it easier to identify which dependency is missing if a command fails.
Should I use library() or require()?
Use library() for most scripts because it clearly stops with an error when a package is unavailable. Use require() when your code deliberately needs to test whether loading succeeded and handle a failure.
How do I use a package function without loading the package?
Use the double-colon operator, as in package_name::function_name(). The package must still be installed, but you do not need to attach it with library().
Why does R say a function could not be found after loading a package?
The function may be misspelled, may belong to another package, or may not be exported for direct use. Check the package documentation and try calling it with package_name::function_name().
Related
- Why Is the Ocean Becoming More Acidic?
- How to Store Kefir Grains in the Fridge
- Oral Thrush: How to Treat It and When to Get Help
Further reading: R Project. Details can change, so check the official page for anything that matters to you. Spotted a mistake? Tell us. How we write an answer.