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.
1 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 | 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!
Be First to Comment