我将library()添加到if函数时出错

时间:2015-03-25 16:11:18

标签: r function

我已经访问了question关于如何实现一个脚本来检查是否加载了正确的包但当我尝试修改代码以执行其他操作时,它们都不起作用,例如,加载列出的如果已经安装了包,或者取一个包列表而不必逐个输入它们。

我尝试了什么:

# works for checking whether individual packages are installed and if not 
# installing them (wrapped in a function to save space)

    chinst <- function(x){if(x %in% rownames(installed.packages())==FALSE) {install.packages(x)}}
    chinst("car")

# (NOT functioning) can't add an `library()` to the if function

    chinst2 <- function(x){if(x %in% rownames(installed.packages())==FALSE) {if(x %in% rownames(available.packages())==FALSE) {paste(x,"is not a valid package name via CRAN")} else {install.packages(x)}} else {library(x)}}

# (NOT Functioning) check a list of packages rather than individual ones

    pkgs <- list("MCMCpack", "BMA", "coda")
    lapply(X = pkgs, FUN = chinst)

1 个答案:

答案 0 :(得分:2)

我觉得这样的事可能适合你。而不是pkgs的包名列表,请使用字符向量。

fun <- function(pkgs) {
    ## check for installed packages
    have <- pkgs %in% rownames(installed.packages())
    ## if we don't have them all, install the ones we don't have
    if(!all(have)) install.packages(pkgs[!have]) 
    ## load them all
    invisible(lapply(pkgs, require, character.only = TRUE))
}

fun(c("MCMCpack", "BMA", "coda"))

请注意,根据.libPaths()的设置,使用.packages(TRUE)通常会返回与rownames(installed.packages())相同的速度,并且速度要快得多。

另请注意,对我来说,rownames(installed.packages())并不可靠。见this Q&A