Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing package name as argument in R

Tags:

function

r

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.

like image 969
Stat-R Avatar asked Feb 25 '13 20:02

Stat-R


Video Answer


1 Answers

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
like image 127
Josh O'Brien Avatar answered Oct 21 '22 17:10

Josh O'Brien