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

September 24, 2017
By

(This article was first published on RLang.io | R Language Programming, and kindly contributed to R-bloggers)

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 on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)