如果未安装,请安装软件包(库) [英] Install package (library) if not installed

查看:175
本文介绍了如果未安装,请安装软件包(库)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中使用了几个软件包,但是我正在可能已安装或未安装某些/所有软件包的计算机上运行脚本.

I am using a couple of packages in R, but I am running the script in a machine that may or may not have some/all of the packages installed already.

软件包有zooquantmoddata.table,...等.

The packages are zoo, quantmod, data.table,..., and a bunch more.

这是我尝试过的: 有没有什么方法可以检查每个软件包是否已安装(如果未安装)?我不想R浪费时间重新安装任何已经存在的软件包.

This is what I have tried: Is there any way of checking if each of these packages is installed, if not install it? I don't want R to waste time reinstalling any package that is already there.

这是我尝试过的:

pckg = c("zoo", "tseries", "quantmod", "MASS", "graphics", "plyr", "data.table", "gridExtra") 

 is.installed <- function(mypkg){
    is.element(mypkg, installed.packages()[,1])
 } 

 for(i in 1:length(pckg)) {
    if (!is.installed(pckg[i])){
         install.packages(pckg[i])
     }
 }

有更好的方法吗?

此外,我需要自动为安装设置镜像.我不知道该怎么做.

Also, I need to automatically set a mirror for the install.I have no idea how to do so.

谢谢!

推荐答案

我使用了此便捷功能,而不是library,如果缺少该软件包,它将安装该软件包,然后require s

I have this convenience function that I use instead of library which installs the package if it is missing, then requires it:

usePackage <- function(p) {
    if (!is.element(p, installed.packages()[,1]))
        install.packages(p, dep = TRUE)
    require(p, character.only = TRUE)
}

如果需要全局选择CRAN镜像,这是一种方法:

In case if you need to select CRAN mirror globally, here is one way to do it:

r <- getOption("repos")
r["CRAN"] <- "http://cran.us.r-project.org"
options(repos = r)
rm(r)

这篇关于如果未安装,请安装软件包(库)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆