【问题标题】:How can I see what are packages being used for in an R script, and which packages are currently not used?如何查看 R 脚本中正在使用哪些包,以及当前未使用哪些包?
【发布时间】:2021-10-15 03:38:04
【问题描述】:

我正在继承一些代码,我认为还有空间进行整理,包括整理包游戏。

特别是,我想查看已加载的包用于什么,以及(最重要的是)是否有任何已加载但未使用的包。

代码很长,包也很多,所以我肯定更喜欢自动化这个过程。

举个小例子,如果我有:

packageload <- c("ggplot2", "readxl")
lapply(packageload, library, character.only = TRUE)

ggplot(diamonds, aes(x = cut)) +
  geom_bar()

我想要一些输出告诉我 ggplot() 是从 ggplot2 使用的(因此被用作包),并且 readxl 目前没有在项目代码中使用。

【问题讨论】:

    标签: r optimization package


    【解决方案1】:

    我一直在寻找一个明确的答案,最后,在@eh21 here 指出的有用函数的基础上,我用 3 行代码构建了这个符合意图并且可以复制的小方法任何人(我的意思是像我这样没有经验的程序)都毫不费力地处理他们的案件。

    原理是在包被加载之后,在实际项目代码之前(即不需要运行它来获得所需的信息)使用这种方法,如下所示:

    # Load packages ----
    
    packageload <- c("ggplot2", "readxl")
    lapply(packageload, library, character.only = TRUE)
    
    
    # Find which packages do used functions belong to ----
    
    used.functions <- NCmisc::list.functions.in.file(filename = "thisfile.R", alphabetic = FALSE) |> print()
    
    
    # Find which loaded packages are not used ----
    
    used.packages <- used.functions |> names() |> grep(pattern = "packages:", value = TRUE) |> gsub(pattern = "package:", replacement = "") |> print()
    
    unused.packages <- packageload[!(packageload %in% used.packages)] |> print()
    
    
    # Actual project code (no need to be run) ----
    
    ggplot(diamonds, aes(x = cut)) +
      geom_bar()
    

    相关的输出是:

    > used.packages
    [1] "base"    "ggplot2"
    
    > used.functions
    $`character(0)`
    [1] "list.functions.in.file"
    
    $`package:base`
    [1] "c"      "lapply" "print"  "names"  "grep"   "gsub"   
    
    $`package:ggplot2`
    [1] "ggplot"   "aes"      "geom_bar"
    
    > unused.packages
    [1] "readxl"
    

    注意事项:

    • 这需要install.packages("NCmisc"),但是我没有加载那个包(而是使用::)以保持一致性,因为它不应该出现在used.packages中;
    • 如果使用 RStudio 并希望将其应用于多个脚本,使用 rstudioapi::getSourceEditorContext()$path 代替 NCmisc::list.functions.in.file 中的 "thisfile.R" 会很方便。
    • 上述方法适用于在命名对象上使用lapply() 以加载包的情况。如果在不使用命名对象的情况下加载包(例如,使用一系列 library()require()),则 #Load packages ---- 部分上面的代码可以修改如下:
    # Load packages ----
    
    packageload <- search()
    
    library(ggplot2)
    library(readxl)
    
    packageload <- search()[!(search() %in% packageload)] |> grep(pattern = "package:", value = TRUE) |> gsub(pattern = "package:", replacement = "")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-05
      • 1970-01-01
      • 1970-01-01
      • 2015-04-15
      • 2021-04-24
      • 2017-12-04
      • 2016-03-06
      • 1970-01-01
      相关资源
      最近更新 更多