Site icon R-bloggers

One Line to Get and Print All Loaded Library Packages in R

[This article was first published on RLang.io | R Language Programming, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

This function is really only useful for those of us who try to rapidly develop a script to give our output, whether it is a plot in ggplot, CSV file, or an html widget. Today I was working on a script which utilized the leaflet R package among some other libraries which was slowly devolving into something less maintainable than I prefer.

Anyhow, if you ever get to the point where you want to retroactively add the library calls to the beginning of your script based on what you have currently loaded, this is for you.

cat(sapply(search()[grep("package:",search())],function(x){return(paste0('library("',gsub("package:","",x),'")','\n'))}))

It is a simple one-liner which has made my life a little easier. Broken down you get

cat( #removes the [1] lines 
  sapply( #apply to the vector
    #search shows everything, so we limit it to package:name
    search()[grep("package:",search())],function(x){ 
      return(
        paste0(
          'library("',
          gsub("package:","",x), #remove "package:" for inclusion
          '")','\n')
      )
    }
  )
)

Which outputs EVERYTHING. You might want to trim it down farther.

library("htmlwidgets")
library("devtools")
library("mapview")
library("leaflet.extras")
library("leaflet")
library("stats")
library("graphics")
library("grDevices")
library("utils")
library("datasets")
library("methods")
library("base")

Hope this helps some others!

To leave a comment for the author, please follow the link and comment on their blog: RLang.io | R Language Programming.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.