Workspace Management

# If you have a big project, it makes sense to break up your code into several
# R-scripts.  From one script, you can call another using the following
# command:

source("mySeparateScript.R")  # load/run external script
# You can also store all objects (the whole current workspace) to an
# .RData-file, which you can load in other scripts:


# Save all objects from the current workspace to an '.RData'-file:
save.image(file = "myWorkspace.RData")

# Load the workspace from the file:
load("myWorkspace.RData")
# To keep the workspace tidy/lean even in a longer code, one can use lists to
# store a collection of objects in a single object; a list.  If in each
# iteration of a loop a plot is created, we can save all these plots into one
# list using the following commands:

lMyPlots = list()  # create empty list before loop

for (ii in 1:10) {

    # create plot for iteration ii, something like this comes out: (as a matter
    # of fact, typically, a plot is saved as a list (containing its
    # attributes); see below)
    plotHere = list(1, "a", "b")

    # save plot to 'lMyPlots':
    lMyPlots = append(lMyPlots, list(plotHere))

    # and assign a name to this plot:
    nameForThisPlot = paste("plot", ii, sep = "_")

    if (ii == 1) {
        # at the first iteration, lMyPlots is empty, so use this:
        names(lMyPlots) = c(names(lMyPlots), nameForThisPlot)
    } else {
        # later on, we can just use this:
        names(lMyPlots)[ii] = nameForThisPlot
    }

}

# The same code can be used to store different regressions into a single list.
# See the section 'Econometrics/Linear Regressions' for how to run regressions
# in a loop.
# Saving a collection of different objects into a single list also enables us
# to delete a bunch of objects at once.  This way, at the end of some longer
# section of code in our script, we can delete all objects that aren't
# necessary for subsequent computations:

a <- 4
b <- 3

# remove all objects but these two:
rm(list = ls()[!(ls() %in% c("lMyList", "lMyPlots"))])


# If you want to iteratively (e.g. after each section of your code) delete a
# bunch of objects, use this code:

a <- 4
b <- 3

# Define a vector containing the names of the objects you want to keep:
vToKeep = c("vToKeep", "lMyList", "a")
# Delete all objects but these:
rm(list = ls()[!(ls() %in% vToKeep)])

# At a later point, once you created some new objects ...:
b <- 3
c <- 5
# ... add the newly created objects that you want to keep to vToKeep ...:
vToKeep = c(vToKeep, "b")
# ... and delete all the rest:
rm(list = ls()[!(ls() %in% vToKeep)])

# (note that vToKeep contains the name of 'vToKeep' itself, otherwise this
# vector would be deleted too)