Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 8

Loading R Packages with `library()`

Recommended resources

Introduction

In our last lesson, you successfully outfitted your R workshop by installing the essential packages for meta-analysis, including meta and tidyverse. These tools are now stored on your computer, ready for use. This lesson focuses on the crucial next step: bringing those tools into your active R session so you can use their functions. We will cover the library() function, which is the command you'll use at the start of every analysis to "load" the packages you need.

This bridges the gap between installation and application. By the end of this lesson, you will understand how to make the powerful functions within packages like tidyverse and meta available for your work, setting the stage for importing and manipulating data in our upcoming lessons.


From Shelf to Workbench: Loading a Package

As we touched on previously, installing a package is a one-time action, like placing a specialized textbook on your shelf. However, to use the knowledge in that book, you need to take it off the shelf and open it on your desk. In R, this action is called loading a package.

You must load a package every time you start a new R session (e.g., after restarting RStudio) to make its functions available. This is done for two main reasons:

  1. Efficiency: R would be slow and memory-intensive if it loaded every single installed package automatically. By loading only what you need for a specific task, you keep your environment lean and efficient.
  2. Avoiding Conflicts: Different packages, sometimes written by different authors, can occasionally have functions with the same name. By explicitly loading only the packages you intend to use, you control which version of a function is active, preventing confusion.

This video offers a great analogy, comparing packages to apps on your phone. Installing is a one-time download; loading with library() is like tapping the app icon to open it for use.

Learn R in 39 minutes

The video "Learn R in 39 minutes" provides a clear and intuitive explanation for loading packages.

Please watch the following two short clips: First, watch the section from the beginning of the package explanation, which introduces the library() command and the "app" analogy. Then, watch the brief clarification from this point, which reinforces that installation is done once, but loading happens in every session.


The library() Function

The standard way to load a package in a reproducible script is with the library() function. The syntax is straightforward. To load a package named packagename, you would write:

library(packagename)

Notice a key difference from the install.packages() function we used in the last lesson: the package name is not in quotes. This is a common point of confusion for newcomers, so it's worth remembering.

  • install.packages("packagename") -> needs quotes.
  • library(packagename) -> no quotes.

The following resource explains this distinction clearly.

Chapter 7 Understanding and Using R Packages

This article from R Programming in Plain English contrasts installing and loading, focusing on the commands you type in your script.

Please read the section titled The Old Fashioned Way. Focus on the two key functions introduced and the note about the difference in notation (the use of quotation marks). Then, look at the code example that follows.


Building a Reproducible Script

Your goal is to create a complete and reproducible script for your meta-analysis. A crucial part of this is declaring all the necessary packages at the very beginning of your script. This ensures that anyone (including your future self) who runs the script will have the correct tools loaded before any analysis is attempted.

Let's put this into practice.

  1. Open RStudio.
  2. Create a new R script by going to File > New File > R Script. An empty script editor will open in the top-left pane.
  3. In this new script, type the following commands at the top. These are the main packages we installed and will rely on for this course.



# Load required packages for meta-analysis
library(tidyverse)
library(meta)
library(metafor)

Now, execute each line by placing your cursor on it and pressing Ctrl+Enter (on Windows) or Cmd+Enter (on Mac).

When you load tidyverse, you will see several messages appear in the console. This is normal. The tidyverse is a collection of packages, and R is telling you which ones have been loaded and if any function names conflict with functions from other packages you might have loaded. These messages are informational, not errors.

You can also look at the Packages tab in the bottom-right pane of RStudio. You'll see that the checkboxes next to tidyverse, meta, and metafor are now ticked, visually confirming they are loaded.


Why This Matters: An Example

Let's see why loading a package is essential. The tidyverse package includes a powerful sub-package called dplyr for data manipulation. It contains functions like group_by() and summarise(), which are incredibly useful for calculating summary statistics—a common task when preparing data for meta-analysis.

Imagine we have data from a small physical therapy trial with two groups (Treatment and Control) and their post-intervention pain scores (on a 0-10 scale).

First, let's create a data frame in R with this information. You can type this code directly into your console or add it to your script and run it.




# Create a sample data frame of patient data
patient_data <- data.frame(
  group = c("Treatment", "Treatment", "Control", "Treatment", "Control", "Control"),
  pain_score = c(3, 4, 7, 5, 6, 8)
)

Now, let's try to calculate the mean pain score for each group using dplyr's functions.




# Calculate mean pain score per group
patient_data %>% 
  group_by(group) %>% 
  summarise(mean_pain = mean(pain_score))

If you have successfully run library(tidyverse), this code will work perfectly and produce a table showing the mean pain score for the Control and Treatment groups.

However, if you had not loaded tidyverse, R would produce an error like Error in group_by(...) : could not find function "group_by". This is because without loading the package, R has no idea what the group_by() function is. This simple example illustrates that library() is the key that unlocks the functionality of your installed packages.


Conclusion

You have now completed the workflow for using R packages: you know how to install them from CRAN and how to load them into your R session for use. This foundational skill is one you will use in every single R project.

Here are the key takeaways from this lesson:

  • Installed packages must be loaded into each new R session before their functions can be used.
  • The library(packagename) command is used to load a package. Unlike install.packages(), it does not use quotes.
  • For reproducible research, library() commands should be placed at the top of your R script to declare all dependencies.

Now that you have your tools installed and loaded, you are ready to start working with data. In the next module, we will begin exploring the tidyverse package in more detail, starting with how to import data from common file formats like CSV and Excel into R.