I see myself keep using the install.package
function a lot especially when I have to try out someone else's code or run an example.
I as writing a function that installs and loads a package. I tried the following but it did not work:
inp <- function(PKG)
{
install.packages(deparse(substitute(PKG)))
library(deparse(substitute(PKG)))
}
When I typed inp(data.table)
, it says
Error in library(deparse(substitute(PKG))) :
'package' must be of length 1
How do I pass library name as argument in this case?
I will appreciate if someone can also direct me to information pertaining to passing any kind of object as argument to a function in R
.
library()
is throwing an error because it by default accepts either a character or a name as its first argument. It sees deparse(substitute(PKG))
in that first argument, and understandably can't find a package of that name when it looks for it.
Setting character.only=TRUE
, which tells library()
to expect a character string as its first argument, should fix the problem. Try this:
f <- function(PKG) {
library(deparse(substitute(PKG)), character.only=TRUE)
}
## Try it out
exists("ddply")
# [1] FALSE
f(plyr)
exists("ddply")
# [1] TRUE
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