1

What I'm trying to do is plain straight forward:

required_pkgs <- c("A", "B", "C")

for (pkg in required_pkgs) {
   library(pkg)
}

At runtime, the R interpreter tries to lookup (3 times) a package called "pkg" (and of course it fails at the first try), when I do expect it to be either "A", "B", "C".

Of course My ignorance of the language makes me miss the point, but why it behaves like that? Does R expects me to write the following code:

library(A)
library(B)
library(C)

I do need to iterate over each package loading to handle missing packages and fallback to installing it or pick an alternative.

BASICALLY I was whining for not being able to iterate over the array of packages names and each call to library with the for parameter (pkg) resulted in R trying to load a non-existent pkg library. This is solved by adding the character.only=TRUE argument a the invocation of library.

EDIT: more infos, sorry for being so vague...

Giupo
  • 413
  • 2
  • 9
  • 1
    Found the answer by myself here: http://stat.ethz.ch/R-manual/R-devel/library/base/html/library.html and the param `character.only` will solve my issue. – Giupo Dec 02 '13 at 09:28
  • 1
    See http://stackoverflow.com/questions/8175912/load-multiple-packages-at-once – zx8754 Dec 02 '13 at 13:38
  • Thank you @zx8754! That's a good one. Probably the answer to this question/doubt would be my own previous comment. – Giupo Dec 02 '13 at 13:44

2 Answers2

3

You saved A,B and C in required_pkgs then modify your code as: library(required_pkgs[pkg]) in for loop instead of library(pkg)

jay_phate
  • 439
  • 3
  • 14
  • I don't think this is the correct answer; some thing like : `required_pkgs=c("A","B","C"); for(pkg in required_pkgs) library(required_pkgs[pkg])` doesn't do what I was looking after (loading "A", "B", "C") – Giupo Dec 02 '13 at 13:15
2

Or, if you wanna install three packages at a time, you can use following code of R: install.packages(c("A", "B", "C")), still if its not gonna work elaborate your question properly.

jay_phate
  • 439
  • 3
  • 14
  • My first comment resolves my question. I fell in panic before reading accurately the docs, even though is counter intuitive. I should have forgotten `for` and go straight to `library(required_pkgs)`. – Giupo Dec 02 '13 at 14:14