如何避免污染当前作用域(使用 `library(...)`)

How to avoid polluting the current scope (with `library(...)`)

作为一项长期政策,我避免将名称导入(又名 "polluting")当前范围,而是在引用不同包中定义的项目时使用完全限定名称。

下面的脚本表明,在 R 中,使用限定名称本身是不够的。

#!/usr/bin/env Rscript

set.seed(0)

x <- local({
         x0 <- matrix(rnbinom(80, size = 5, mu = 10), nrow = 20)
         `rownames<-`(rbind(0, c(0, 0, 2, 2), x0),
                      paste("Tag", 1:(nrow(x0) + 2), sep = "."))
     })

y <- edgeR::DGEList(counts = x,
                    group = rep(1:2, each = 2),
                    lib.size = 1001:1004)

## library(edgeR)

y[1, 1]

脚本失败

Error in y[1, 1] : incorrect number of dimensions
Execution halted

脚本的唯一错误似乎是在失败语句之前的某处没有包含行 library(edgeR),因为如果取消对注释掉的行的注释,错误就会消失。

恕我直言,这是巫术。

有没有办法在不污染当前范围的情况下避免错误 library(edgeR)

当您避免加载 edgeR 包时,您也避免加载执行 y[1, 1] 所必需的 [.DGEList 方法。如果您不想加载 edgeR 库,则需要直接调用提取函数:

edgeR::`[.DGEList`(y, 1, 1)

如果您不喜欢完全限定的语法,可以使用

引入您需要的方法
`[.DGEList` <- edgeR::`[.DGEList`

然后 y[1, 1] 将按预期工作。但这是另一种形式的污染,我不确定我是否会推荐它作为通用解决方案。