Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables to the library function [duplicate]

Tags:

r

load

package <- c("car","ggplot2","pastecs","psych")
for (i in package){
  if (!(i %in% rownames(installed.packages()))){
    install.packages(i)
  } else{
     print(paste(i,"has been installed"))
     library(i)
     }
 }

I wrote a loop to see whether the package is installed, and if it is available, the library should load it.

However I got an error: there is no package called 'i'

Why can't I pass the value in variable i to the library function ?

like image 865
tky Avatar asked Oct 20 '25 13:10

tky


1 Answers

Here's a simpler version of your code (incorporating @csgillespie's suggestion):

p <- c("car","ggplot2","pastecs","psych") 
for(i in seq_along(p)) {
    if(!require(p[i], character.only=TRUE)) {
        install.packages(p[i])
        library(p[i], character.only=TRUE)
    }
}

Note that your code does not work because of non-standard evaluation in library and require. The character.only argument resolves this (per documentation ? library):

character.only
a logical indicating whether package or help can be assumed to be character strings.

like image 129
Thomas Avatar answered Oct 23 '25 05:10

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!