循环以加载或安装软件包不起作用.我做错了什么



我正在学习R,并编写了我的第一个for循环。对于具有所需包(必需包)的字符向量,我尝试创建一个名为 install_load 的函数,用于检查所需包中的包是否已安装。如果是这样,那么它通过 library() 函数加载这些包。否则,它会安装它们。但是,运行代码会给我以下错误:

install.packages 中的错误:更新加载的软件包

正在重新启动 R 会话...

install.packages(p)install.packages 中出错:找不到对象"p"**

requiredpackages <- c('ggplot2', 'ggthemes')
    
install_load <- function(packages){
for (p in packages) {
   if (p %in% rownames(installed.packages())) {
       library(p, character.only=TRUE)
       } else {
       install.packages(p)
           }
         }
       }
    
       install_load(requiredpackages)

将函数中的requiredpackages对象引用更改为packages以解决逻辑错误。由于 packages 是包含传递给函数的包列表的参数的名称,因此它是在函数的 for() 循环中引用的正确对象。

您还需要向安装包的分支添加一个library()函数,以便在函数结束时安装和加载所有必需的包。

requiredpackages <- c('ggplot2', 'ggthemes')
install_load <- function(packages){
     for (p in packages) {
          if (p %in% rownames(installed.packages())) {
               library(p, character.only=TRUE)
          } else {
               install.packages(p)
               library(p,character.only = TRUE)
          }
     }
}
install_load(requiredpackages)

。和输出:

> install_load(requiredpackages)
Want to understand how all the pieces fit together? See the R for Data Science book:
http://r4ds.had.co.nz/
trying URL 'https://cran.rstudio.com/bin/macosx/el-capitan/contrib/3.5/ggthemes_4.0.1.tgz'
Content type 'application/x-gzip' length 425053 bytes (415 KB)
==================================================
downloaded 415 KB

The downloaded binary packages are in
    /var/folders/2b/bhqlk7xs4712_5b0shwgtg840000gn/T//Rtmp1yfVvz/downloaded_packages
> 

我们还可以使用sessionInfo()来确认 ggplot2ggthemes 包都已加载到内存中:

> sessionInfo()
R version 3.5.1 (2018-07-02)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS  10.14.2
Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     
other attached packages:
[1] ggthemes_4.0.1 ggplot2_3.1.0 
...sessionInfo() output continues.

相关内容

最新更新