更新特定的R包及其依赖项

use*_*783 33 r cran

我的系统(服务器)中安装了大约4000个R软件包,其中大多数已经过时,因为它们是在R-3.0.0之前构建的.现在我知道了

update.packages(checkBuilt=TRUE, ask=FALSE)
Run Code Online (Sandbox Code Playgroud)

会更新我的所有包裹,但这太慢了.问题是用户不使用大多数软件包,现在他们要求我更新他们使用的软件包(比如字段).现在,如果我跑

install.packages("fields")
Run Code Online (Sandbox Code Playgroud)

即使字段依赖于地图,它也只会更新包字段而不更新包映射.因此当我尝试加载包字段时:

library("fields")
Run Code Online (Sandbox Code Playgroud)

我收到一条错误消息

Error: package ‘maps’ was built before R 3.0.0: please re-install it
Run Code Online (Sandbox Code Playgroud)

有没有办法升级字段,以便它还会自动更新包字段取决于?

Rei*_*son 16

作为本在他的评论中指出的,你需要得到的依赖关系fields,然后滤出包有优先权"Base"或者"Recommended",再通过包装的该列表install.packages()处理安装.就像是:

instPkgPlusDeps <- function(pkg, install = FALSE,
                            which = c("Depends", "Imports", "LinkingTo"),
                            inc.pkg = TRUE) {
  stopifnot(require("tools")) ## load tools
  ap <- available.packages() ## takes a minute on first use
  ## get dependencies for pkg recursively through all dependencies
  deps <- package_dependencies(pkg, db = ap, which = which, recursive = TRUE)
  ## the next line can generate warnings; I think these are harmless
  ## returns the Priority field. `NA` indicates not Base or Recommended
  pri <- sapply(deps[[1]], packageDescription, fields = "Priority")
  ## filter out Base & Recommended pkgs - we want the `NA` entries
  deps <- deps[[1]][is.na(pri)]
  ## install pkg too?
  if (inc.pkg) {
    deps = c(pkg, deps)
  }
  ## are we installing?
  if (install) {
    install.packages(deps)
  }
  deps ## return dependencies
}
Run Code Online (Sandbox Code Playgroud)

这给出了:

R> instPkgPlusDeps("fields")
Loading required package: tools
[1] "fields" "spam"   "maps"
Run Code Online (Sandbox Code Playgroud)

与...匹配

> packageDescription("fields", fields = "Depends")
[1] "R (>= 2.13), methods, spam, maps"
Run Code Online (Sandbox Code Playgroud)

如果未实际安装依赖项,则会从该sapply()行收到警告.我认为这些是无害的,因为在这种情况下返回的值是,我们用它来表示我们想要安装的包.我怀疑如果您安装了4000个软件包,它会对您产生影响.depsNA

默认情况下不是安装包,而只是返回依赖项列表.我认为这是最安全的,因为您可能没有意识到隐含的依赖链并最终意外地安装了数百个软件包.传入install = TRUE,如果你是幸福的安装指定的包.

请注意,我限制搜索的依赖项的类型 - 如果您使用的话气球which = "most"- 一旦您递归地解析这些依赖项(包括字段),字段就有超过300个这样的依赖项Suggests:.which = "all"将寻找一切,包括Enhances:哪一个将是一个更大的包列表.请参阅参数的?tools::package_dependencies有效输入which.


Met*_*hic 7

我的回答建立在Gavin的答案之上......请注意,原始海报user3175783要求提供更智能的版本update.packages().该功能会跳过安装已更新的软件包.但是Gavin的解决方案会安装一个包及其所有依赖项,无论它们是否是最新的.我使用了Gavin的跳过基础包(实际上不可安装)的提示,并编写了一个也跳过最新包的解决方案.

主要功能是installPackages().此函数及其帮助程序执行拓扑排序,这些依赖树以一组给定的包为根.检查结果列表中的包的陈旧性并逐个安装.这是一些示例输出:

> remove.packages("tibble")
Removing package from ‘/home/frederik/.local/lib/x86_64/R/packages’
(as ‘lib’ is unspecified)
> installPackages(c("ggplot2","stringr","Rcpp"), dry_run=T)
##  Package  digest  is out of date ( 0.6.9 < 0.6.10 )
Would have installed package  digest 
##  Package  gtable  is up to date ( 0.2.0 )
##  Package  MASS  is up to date ( 7.3.45 )
##  Package  Rcpp  is out of date ( 0.12.5 < 0.12.8 )
Would have installed package  Rcpp 
##  Package  plyr  is out of date ( 1.8.3 < 1.8.4 )
Would have installed package  plyr 
##  Package  stringi  is out of date ( 1.0.1 < 1.1.2 )
Would have installed package  stringi 
##  Package  magrittr  is up to date ( 1.5 )
##  Package  stringr  is out of date ( 1.0.0 < 1.1.0 )
Would have installed package  stringr 
...
##  Package  lazyeval  is out of date ( 0.1.10 < 0.2.0 )
Would have installed package  lazyeval 
##  Package  tibble  is not currently installed, installing
Would have installed package  tibble 
##  Package  ggplot2  is out of date ( 2.1.0 < 2.2.0 )
Would have installed package  ggplot2 
Run Code Online (Sandbox Code Playgroud)

这是代码,抱歉长度:

library(tools)

# Helper: a "functional" interface depth-first-search
fdfs = function(get.children) {
  rec = function(root) {
    cs = get.children(root);
    out = c();
    for(c in cs) {
      l = rec(c);
      out = c(out, setdiff(l, out));
    }
    c(out, root);
  }
  rec
}

# Entries in the package "Priority" field which indicate the
# package can't be upgraded. Not sure why we would exclude
# recommended packages, since they can be upgraded...
#excl_prio = c("base","recommended")
excl_prio = c("base")

# Find the non-"base" dependencies of a package.
nonBaseDeps = function(packages,
  ap=available.packages(),
  ip=installed.packages(), recursive=T) {

  stopifnot(is.character(packages));
  all_deps = c();
  for(p in packages) {
    # Get package dependencies. Note we are ignoring version
    # information
    deps = package_dependencies(p, db = ap, recursive = recursive)[[1]];
    ipdeps = match(deps,ip[,"Package"])
    # We want dependencies which are either not installed, or not part
    # of Base (e.g. not installed with R)
    deps = deps[is.na(ipdeps) | !(ip[ipdeps,"Priority"] %in% excl_prio)];
    # Now check that these are in the "available.packages()" database
    apdeps = match(deps,ap[,"Package"])
    notfound = is.na(apdeps)
    if(any(notfound)) {
      notfound=deps[notfound]
      stop("Package ",p," has dependencies not in database: ",paste(notfound,collapse=" "));
    }
    all_deps = union(deps,all_deps);
  }
  all_deps
}

# Return a topologically-sorted list of dependencies for a given list
# of packages. The output vector contains the "packages" argument, and
# recursive dependencies, with each dependency occurring before any
# package depending on it.
packageOrderedDeps = function(packages, ap=available.packages()) {

  # get ordered dependencies
  odeps = sapply(packages,
    fdfs(function(p){nonBaseDeps(p,ap=ap,recursive=F)}))
  # "unique" preserves the order of its input
  odeps = unique(unlist(odeps));

  # sanity checks
  stopifnot(length(setdiff(packages,odeps))==0);
  seen = list();
  for(d in odeps) {
    ddeps = nonBaseDeps(d,ap=ap,recursive=F)
    stopifnot(all(ddeps %in% seen));
    seen = c(seen,d);
  }

  as.vector(odeps)
}

# Checks if a package is up-to-date. 
isPackageCurrent = function(p,
  ap=available.packages(),
  ip=installed.packages(),
  verbose=T) {

    if(verbose) msg = function(...) cat("## ",...)
    else msg = function(...) NULL;

    aprow = match(p, ap[,"Package"]);
    iprow = match(p, ip[,"Package"]);
    if(!is.na(iprow) && (ip[iprow,"Priority"] %in% excl_prio)) {
      msg("Package ",p," is a ",ip[iprow,"Priority"]," package\n");
      return(T);
    }
    if(is.na(aprow)) {
      stop("Couldn't find package ",p," among available packages");
    }
    if(is.na(iprow)) {
      msg("Package ",p," is not currently installed, installing\n");
      F;
    } else {
      iv = package_version(ip[iprow,"Version"]);
      av = package_version(ap[aprow,"Version"]);
      if(iv < av) {
        msg("Package ",p," is out of date (",
            as.character(iv),"<",as.character(av),")\n");
        F;
      } else {
        msg("Package ",p," is up to date (",
            as.character(iv),")\n");
        T;
      }
    }
}

# Like install.packages, but skips packages which are already
# up-to-date. Specify dry_run=T to just see what would be done.
installPackages =
    function(packages,
             ap=available.packages(), dry_run=F,
             want_deps=T) {

  stopifnot(is.character(packages));

  ap=tools:::.remove_stale_dups(ap)
  ip=installed.packages();
  ip=tools:::.remove_stale_dups(ip)

  if(want_deps) {
    packages = packageOrderedDeps(packages, ap);
  }

  for(p in packages) {
    curr = isPackageCurrent(p,ap,ip);
    if(!curr) {
      if(dry_run) {
        cat("Would have installed package ",p,"\n");
      } else {
        install.packages(p,dependencies=F);
      }
    }
  }
}

# Convenience function to make sure all the libraries we have loaded
# in the current R session are up-to-date (and to update them if they
# are not)
updateAttachedLibraries = function(dry_run=F) {
  s=search();
  s=s[grep("^package:",s)];
  s=gsub("^package:","",s)
  installPackages(s,dry_run=dry_run);
}
Run Code Online (Sandbox Code Playgroud)