R Install all package Dependencies

R packages have dependency packages that must be installed and loaded in order for the desired package to be used. Check out my sample R code below to print all dependencies for a certain package and install all of them.

I want to install and load the ggplot2 package with all the dependencies.

#Package below needed to view dependencies
install.packages("miniCRAN")
library(miniCRAN)

#For a given package list all the dependencies and store in an object vector
ggplot2_dep = pkgDep("ggplot2")


#Install all packages and dependencies.
install.packages(ggplot2_dep)
#Below prints number of dependency packages in ggplot2 package
length(ggplot2_dep)
ggplot2_dep