Passing the package name as an argument in R

I see that I often use the install.package function, especially when I have to check another user's code or run an example.

I am writing a function that installs and downloads a package. I tried the following, but this 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 to pass the library name as an argument in this case? I would appreciate it if someone could also direct me to the information related to passing any object as an argument to a function in R

+6
source share
1 answer

library() throws an error because by default it takes a character or name as the first argument. He sees deparse(substitute(PKG)) in this first argument and, for obvious reasons, cannot find a package of this name when he searches for it.

The character.only=TRUE setting, which tells library() expect the character string as the first argument, should fix the problem. Try the following:

 f <- function(PKG) { library(deparse(substitute(PKG)), character.only=TRUE) } ## Try it out exists("ddply") # [1] FALSE f(plyr) exists("ddply") # [1] TRUE 
+8
source

All Articles