Load Multiple Packages in R, The following example demonstrates how to apply this syntax in practice.
Load Multiple Packages in R
Loading Multiple Packages in R as an Example
The code below demonstrates how to summarise a dataset in R and plot it using three different packages:
Dplyr, ggplot2, and ggthemes
In this example, we use three different library() functions to load each package individually:
library(dplyr) library(ggplot2) library(ggthemes)
Let’s make this example reproducible
set.seed(123)
Now we can create a data frame
df <- data.frame(category=rep(c('A', 'B', 'C', 'D', 'E'), each=10), value=runif(50, 10, 20))
head(df) category value 1 A 12.62282 2 A 10.24194 3 A 11.85131 4 A 18.21470 5 A 19.57363 6 A 12.79017
Now we can create a summary data frame
df_summary <- df %>% group_by(category) %>% summarize(mean=mean(value), sd=sd(value))
Let’s plot the mean value of each category with error bars
ggplot(df_summary) + geom_bar(aes(x=category, y=mean), stat='identity') + geom_errorbar(aes(x=category, ymin=mean-sd, ymax=mean+sd), width=0.3) + theme_tufte()
We can use this code to load all three packages and generate a plot that summarises the values in a dataset.
We could, however, achieve the same result by using the lapply() function to load all three packages with just one line of code:
Let’s define the package loading vector
some_packages <- c('ggplot2', 'dplyr', 'ggthemes')
Now we can load all packages at once
lapply(some_packages, library, character.only=TRUE)
Let’s plot the mean value of each category with error bars
ggplot(df_summary) + geom_bar(aes(x=category, y=mean), stat='identity') + geom_errorbar(aes(x=category, ymin=mean-sd, ymax=mean+sd), width=0.3) + theme_tufte()
We can load all three packages again and get the same plot as before.
The difference this time is that we can load all three packages with just one line of code.
This lapply() function comes in handy when you need to load a long list of packages without having to type out the library() function each time.