【问题标题】:Update a specific R package and its dependencies更新特定的 R 包及其依赖项
【发布时间】:2023-03-16 12:46:01
【问题描述】:

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

update.packages(checkBuilt=TRUE, ask=FALSE)

会更新我所有的包,但这太慢了。问题是用户不使用大多数包,他们不时要求我更新他们将使用的包(比如字段)。现在,如果我运行

install.packages("fields")

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

library("fields")

我收到一条错误消息

Error: package ‘maps’ was built before R 3.0.0: please re-install it

有没有办法升级字段,这样它也会自动更新依赖的包字段?

【问题讨论】:

  • 与其尝试重新设计或重写 R 的包系统,不如真正地​​硬着头皮运行update.packages(checkBuilt=TRUE, ask=FALSE)
  • 我会从ap <- available.packages(); pkgs <- tools::package_dependencies("fields",db=ap,recursive=TRUE)开始。然后你需要过滤掉内置和推荐的包,然后安装其余的。 (这不涉及依赖关系图所在的 order,但它可能适用于您的情况。)
  • 不要撤消我对代码使用正确标记所做的编辑!您正在使用 blockquote markdown > 并且您应该使用代码/预 markdown 缩进 4 个空格。
  • 哎呀!我撤消了您的编辑吗?我只是想在 install.packages(fields) 中的字段周围加上双引号。
  • @user3175783 啊,是的,你做到了。没关系。我现在将在引号中进行编辑。希望答案有用吗?可能需要一些工作才能使其防弹,但这是一个开始。此外,请注意 which 参数。如果我使用 fields 执行which = "most",您将需要安装近 400 个软件包!对于一些更受欢迎的软件包,您最终可能会安装大量 CRAN,在这种情况下,您可能会在周末从 CRAN 更新所有软件包。

标签: r cran


【解决方案1】:

正如 Ben 在评论中指出的那样,您需要获取 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
}

这给出了:

R> instPkgPlusDeps("fields")
Loading required package: tools
[1] "fields" "spam"   "maps"

匹配的

> packageDescription("fields", fields = "Depends")
[1] "R (>= 2.13), methods, spam, maps"

您从sapply() 行收到警告如果 deps 中的依赖项实际上并未安装。我认为这些是无害的,因为在这种情况下返回的值是NA,我们用它来指示我们要安装的包。如果您安装了 4000 个软件包,我怀疑它会影响您。

默认是来安装包,而只是返回依赖列表。我认为这是最安全的,因为您可能没有意识到隐含的依赖链并最终意外安装了数百个软件包。如果您愿意安装指定的软件包,请传入install = TRUE

请注意,我限制搜索的依赖类型 - 如果你使用 which = "most",事情会膨胀 - 一旦你递归解决这些依赖(包括 Suggests: 字段),字段就有超过 300 个这样的依赖)。 which = "all" 将查找所有内容,包括 Enhances:,它将再次成为更大的软件包列表。有关 which 参数的有效输入,请参阅 ?tools::package_dependencies

【讨论】:

  • 这成功了!谢谢加文。顺便说一句,我将命令 install.packages(deps) 编辑为 install.packages(c(pkg,deps))
  • 我想,给定我给函数的名称,那么应该进行更改。我会做的,因为其他两个用户拒绝了它。我也会看看我能做些什么,他们不应该这样做。
【解决方案2】:

我的答案基于 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 

这里是代码,抱歉太长了:

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);
}

【讨论】:

  • 如果您投反对票,请在之前或之后发表评论,以便我知道要解决的问题...
  • 可能有人因为这个答案的复杂性而被否决了,但我觉得它非常好,但仍然很复杂
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-05
  • 2021-06-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多