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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With