Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling library() in R with a variable as the argument [duplicate]

Tags:

r

I'd like to achieve something to the effect of

libs = c("AER", "gbm", "caret", "MASS", "nnet", "randomForest")
for (i in libs) {
  if(!is.element(i, .packages()) {
    install.packages(i)
  }
  library(i)
}

The call to library(i) does not replace i with the value being stored in the variable i. Instead, it tries to load the library called "i"

Is there a way to force i to be treated as a variable and resolved before the call to the library?

like image 620
DanB Avatar asked Mar 09 '12 01:03

DanB


People also ask

How do you pass a function as an argument in R?

We can pass an argument to a function while calling the function by simply giving the value as an argument inside the parenthesis. Below is an implementation of a function with a single argument.

Can I call a function inside another function in R?

Nested Function Calls in R Now consider the arguments: these can be of any type and can have default values inside the function. The latter provides an output even when explicit values are not passed to it. Finally, you can call another function within a function.

How do you call a function from a package in R?

Every time you start a new R session you'll need to load the packages/libraries that contain functions you want to use, using either library() or require() . If you load a package with the same function name as in another package, you can use packageName::functionName() to call the function directly.

How do you install a package in R?

Open R via your preferred method (icon on desktop, Start Menu, dock, etc.) Click “Packages” in the top menu then click “Install package(s)”. Choose a mirror that is closest to your geographical location. Now you get to choose which packages you want to install.


2 Answers

How about library(...,character.only = TRUE)?

like image 150
joran Avatar answered Oct 10 '22 03:10

joran


Here is the full code (combining joran's answer and adding "all.available = TRUE" ).

libs = c("AER", "gbm", "caret", "MASS", "nnet", "randomForest")
for (i in libs){
  if( !is.element(i, .packages(all.available = TRUE)) ) {
    install.packages(i)
  }
  library(i,character.only = TRUE)
}
like image 31
Stanislav Avatar answered Oct 10 '22 02:10

Stanislav