0

I use this code in my Rprofile.site to load packages when I start 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)
})

It works just fine but prints [1] TRUE TRUE TRUE TRUE to the console. I know I can divert stdout using textConnection(); sink(); [code]; sink(); close(), but that seems like a lot of work. Is there a way to do this with less typing?

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)
Josh
  • 1,210
  • 12
  • 30
  • You just want to not print `TRUE` to the console? Can you just use `library()`? – Calum You Aug 07 '18 at 22:42
  • @Calum You, I probably can just use `library()`. I used `require()` because of this comment in the `library()` documentation: "`require` is designed for use inside other functions; it returns FALSE and gives a warning (rather than an error as `library()` does by default) if the package does not exist". Since I'm only loading packages I know I've installed, `library()` should work. – Josh Aug 08 '18 at 03:40

1 Answers1

2

Options:

  1. You can use invisible on the output from apply to remove the outputs.

  2. Or you can use the pacman package to perform what you are doing.

  3. Or the below code should be more concise (See 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. Or write an R package to make your dependencies explicit.
chinsoon12
  • 25,005
  • 4
  • 25
  • 35
  • `invisible(apply())` worked perfectly. Thanks. -edit- And now I'm installing `pacman`! -edit- – Josh Aug 08 '18 at 03:58