8

すべての依存関係を含むパッケージをアンロードしようとしています。私が直面している問題は、依存関係をアンロードする順序です。依存関係は再帰的であるため、依存関係ツリーのボトムアップからのみアンロードできます。

これを達成するためのRで簡単またはネイティブな方法はありますか? 以下は、私が達成したいことの最初の行です。

eval_current <- function(expr, envir=parent.frame(), timeout=60){  
  #set the timeout
  setTimeLimit(elapsed=timeout, transient=TRUE);

  #currently loaded packages
  currentlyattached <- search();
  currentlyloaded <- loadedNamespaces();

  on.exit({
    #reset time limit
    setTimeLimit(cpu=Inf, elapsed=Inf, transient=FALSE);

    #try to detach packages that were attached during eval
    nowattached <- search();
    todetach <- 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 <- loadedNamespaces(); 
    tounload <- nowloaded[!(nowloaded %in% currentlyloaded)];
    for(i in seq_along(tounload)){
      try(unloadNamespace(tounload[i]));
    }    

  });

  eval(expr, envir) 
}

しかし、結果は次のとおりです。

> 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
4

1 に答える 1

2

これは私にとってはうまくいきます-少し粗雑ですが、仕事は完了します。

on.exit({
  #reset time limit
  setTimeLimit(cpu=Inf, elapsed=Inf, transient=FALSE);

  #try to detach packages that were attached during eval
  nowattached <- search();
  todetach <- nowattached[!(nowattached %in% currentlyattached)];
  while( ! length(todetach) == 0 ){
    for(i in seq_along(todetach)){
      suppressWarnings(tryCatch(detach(todetach[i], unload=TRUE, character.only=TRUE, force=TRUE),error = function(x) return(NA)))
    }
    nowattached <- search();
    todetach <- sample(nowattached[!(nowattached %in% currentlyattached)]);
  }

  #try to unload packages that are still loaded
  nowloaded <- loadedNamespaces(); 
  tounload <- nowloaded[!(nowloaded %in% currentlyloaded)];
  while( ! length(tounload) == 0 ){
    for(i in seq_along(todetach)){
      suppressWarnings(tryCatch(unloadNamespace(tounload[i]),error = function(x) return(NA)))
    }
    nowloaded <- loadedNamespaces(); 
    tounload <- sample(nowloaded[!(nowloaded %in% currentlyloaded)]);
  }
});
于 2015-01-13T16:05:33.130 に答える