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!