Section 1.4 R Packages (How To Install and Load Packages)
The basic R functions that come with the software are highly versatile but have limitations. Additional functions are available in packages developed by researchers and contributors worldwide to extend R’s capabilities, which are then integrated into the R open-source platform. Throughout this textbook, we will leverage many of these packages. One widely used package we will incorporate is the
tidyverse package. The tidyverse encompasses various R packages tailored for data science and statistical analysis — simply, it is a package that contains multiple packages. These packages synergistically interact to offer a unified framework for data manipulation, visualization, and analytics. Let’s practice installing a package and operating it.
Before using a package, you must first install it. You can accomplish the installation by using the R function
install.packages(), as illustrated below:
install.packages("tidyverse")
After installing the
tidyverse package, it needs to be loaded for use. Unlike the installation process, each time you wish to use a package, it must be loaded beforehand.
# Load the tidyverse package
library(tidyverse)
To briefly demonstrate how you can use the loaded package, we will use the built-in
USArrests dataset. You do not need to download this since the USArrests dataset is actually embedded in the basic R package. The dataset includes information on the number of arrests per 100,000 residents for assault, murder, and rape from the 50 US states in 1973. Additionally, it provides for the percentage of the population residing in urban areas. Using the tidyverse package, we filter the dataset to include only certain states and visualize the relationship between the two variables below. Specifically, we filter the dataset to include only states with a murder rate above 7 and then visualize the number of assaults per 100,000 annually and the percent of the state population living in urban areas using a scatter plot.
# Print the first few rows of the dataset
print(head(USArrests))
# Filter the dataset to include only states with a murder rate above 7
filtered_data <- USArrests %>%
filter(Murder > 7)
# Print the filtered dataset
print(filtered_data)
# Visualize the relationship between Assault and UrbanPop
ggplot(filtered_data, aes(x = Assault, y = UrbanPop)) +
geom_point() +
labs(title = "Relationship between Assault and UrbanPop",
x = "Assault", y = "UrbanPop") + theme_minimal()
