在R中将包名称作为参数传递

Sta*_*t-R 6 r function

我发现自己一直在使用这个install.package功能,特别是当我必须尝试别人的代码或运行一个例子时.

我正在编写一个安装和加载包的函数.我尝试了以下但它不起作用:

inp <- function(PKG)
{
  install.packages(deparse(substitute(PKG)))
  library(deparse(substitute(PKG)))
}
Run Code Online (Sandbox Code Playgroud)

当我输入时inp(data.table),它说

Error in library(deparse(substitute(PKG))) : 
  'package' must be of length 1
Run Code Online (Sandbox Code Playgroud)

在这种情况下,如何将库名称作为参数传递?如果有人也可以指导我将任何类型的对象作为参数传递给函数,我将不胜感激R.

Jos*_*ien 9

library()抛出错误,因为它默认接受字符名称作为其第一个参数.它deparse(substitute(PKG))在第一个参数中看到,并且可以理解的是在找到它时找不到该名称的包.

设置character.only=TRUE,告诉library()期望字符串作为其第一个参数,应该解决问题.试试这个:

f <- function(PKG) {
    library(deparse(substitute(PKG)), character.only=TRUE)
}

## Try it out
exists("ddply")
# [1] FALSE
f(plyr)
exists("ddply")
# [1] TRUE
Run Code Online (Sandbox Code Playgroud)