title: Unload a package and all dependencies
body: <p>I am trying to unload a package with all of its dependencies. The problem that I am running into is the order in which to unload dependencies. Because dependencies are recursive, they can only be unloaded from bottom-up in the dependency tree.</p>
  
  <p>Is there an easy or native way in R to accomplish this? Below a first go in what I would like to accomplish:   </p>
  
  <pre><code>eval_current &lt;- function(expr, envir=parent.frame(), timeout=60){  
    #set the timeout
    setTimeLimit(elapsed=timeout, transient=TRUE);
  
    #currently loaded packages
    currentlyattached &lt;- search();
    currentlyloaded &lt;- loadedNamespaces();
  
    on.exit({
      #reset time limit
      setTimeLimit(cpu=Inf, elapsed=Inf, transient=FALSE);
  
      #try to detach packages that were attached during eval
      nowattached &lt;- search();
      todetach &lt;- nowattached[!(nowattached %in% currentlyattached)];
      for(i in seq_along(todetach)){
        try(detach(todetach[i], unload=TRUE, character.only=TRUE, force=TRUE));
      }
  
      #try to unload packages that are still loaded
      nowloaded &lt;- loadedNamespaces(); 
      tounload &lt;- nowloaded[!(nowloaded %in% currentlyloaded)];
      for(i in seq_along(tounload)){
        try(unloadNamespace(tounload[i]));
      }    
  
    });
  
    eval(expr, envir) 
  }
  </code></pre>
  
  <p>But it results in:</p>
  
  <pre><code>&gt; eval_current({library(ggplot2); qplot(rnorm(100));})
  Error in unloadNamespace(tounload[i]) : 
    namespace ‘colorspace’ is imported by ‘munsell’ so cannot be unloaded
  Error in unloadNamespace(tounload[i]) : 
    namespace ‘dichromat’ is imported by ‘scales’ so cannot be unloaded
  Error in unloadNamespace(tounload[i]) : 
    namespace ‘grid’ is imported by ‘gtable’ so cannot be unloaded
  Error in unloadNamespace(tounload[i]) : 
    namespace ‘labeling’ is imported by ‘scales’ so cannot be unloaded
  Error in unloadNamespace(tounload[i]) : 
    namespace ‘munsell’ is imported by ‘scales’ so cannot be unloaded
  </code></pre>