代码之家  ›  专栏  ›  技术社区  ›  Josh

转移require()的输出

r
  •  0
  • Josh  · 技术社区  · 7 年前

    我在rprofile.site中使用此代码在启动r时加载包。

    pkg <- c("dplyr", "tidyr", "crayon", "xlsx")
    apply(as.matrix(pkg), 1, function(x) {
        if (!x %in% utils::installed.packages()) {
            utils::install.packages(x)
            cat(paste0("package ", x, " installed\n"))
        }
        x <- require(x, character.only = T)
    })
    

    它很好用,不过是印刷品 [1] TRUE TRUE TRUE TRUE 到控制台。我知道我可以转移注意力 stdout 使用 textConnection(); sink(); [code]; sink(); close() 但这似乎是很多工作。有没有办法减少打字量?

    tc <- textConnection("outputs","w")
    sink(tc, type="output")
        pkg <- c("dplyr", "tidyr", "crayon", "xlsx")
        apply(as.matrix(pkg), 1, function(x) {
            if (!x %in% utils::installed.packages()) {
                utils::install.packages(x)
                cat(paste0("package ", x, " installed\n"))
            }
            require(x, character.only = T)
        })
    sink(NULL, type="output")
    close(tc)
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   chinsoon12    7 年前

    选项:

    1. 你可以用 invisible 在输出上 apply 移除输出。

    2. 或者你可以使用 pacman 打包以执行您正在执行的操作。

    3. 或者下面的代码应该更简洁(请参见 Check for installed packages before running install.packages() ):

    invisible(lapply(pkg, function(x) {
        if (!nzchar(system.file(package=x)))
            install.packages(x)
        library(x, character.only=TRUE)
    }))
    
    1. 或者编写一个r包,使依赖关系显式化。