gpt4 book ai didi

删除 R 中未使用的库

转载 作者:行者123 更新时间:2023-12-02 01:52:08 25 4
gpt4 key购买 nike

所以我刚刚写完第一个脚本来从文本文件组装威 bool 分析。在我所有的修改中,我怀疑我可能加载了一些最终脚本中未使用的库。有没有一种快速方法可以检查脚本正在使用哪些库,而无需检查每个函数?

最佳答案

这是一个脚本,它应该找到您已加载但未在脚本中使用的包。它需要在干净的 session 中运行,因为无法验证当前 session 的状态是否与脚本将创建的状态相同。它假设包仅使用 libraryrequire 加载,无论如何,这是一个很好的做法。我没有对其进行广泛的测试,但看起来相当合理。

代码如何工作的解释在注释中。这是一个有趣的练习,纯粹用 R 语言编写,这样它本身就不必加载任何包。

使用getParseData作为起点的想法来自Eric Green's answer to this related question

# Define the file to test in the line below. That is the only per-run configuration needed.
fileToTest <- "Plot.R"

# Get the parse data for the file
parseData <- getParseData(parse(fileToTest), includeText = TRUE)

# Extract all the function calls and keep a unique list of them.
functionCalls <- unique(parseData[parseData$token == "SYMBOL_FUNCTION_CALL", "text"])

# Look for any calls to `library` or `require` and go two steps up the
# call tree to find the complete call (with arguments).
libraryCalls <- parseData[parseData$token == "SYMBOL_FUNCTION_CALL" & parseData$text %in% c("library", "require"),]
libraryCalls <- parseData[parseData$id %in% libraryCalls$parent,]
libraryCalls <- parseData[parseData$id %in% libraryCalls$parent,]
libraryCalls <- libraryCalls$text

# Execute all the library/require calls to attach them to this session
eval(parse(text = libraryCalls))

# For each function called,
# * Use `getAnywhere` to find out where it is found. That information is in a character
# vector which is the `where` component of the returned list.
# * From that vector of locations, keep only the ones starting with "package:",
# getting rid of those starting with "namespace:".
# * Take the first one of these which sould be the first package that the
# function is found in and thus would be the one used.
names(functionCalls) <- functionCalls
matchPkg <- vapply(functionCalls,
FUN = (\(f) grep("^package:", getAnywhere(f)$where, value = TRUE)[1]),
FUN.VALUE = character(1))

# get a list of all packages from the search path, keep only those that are
# actually packages (not .GlobalEnv, Autoloads, etc.), ignore those that are
# automatically attached (base, methods, datasets, utils, grDevices, graphics, stats),
# and then see of those which ones did not show up in the list of packages used
# by the functions.
packages <- search()
packages <- grep("^package:", packages, value = TRUE)
packages <- setdiff(packages, c("package:base", "package:methods", "package:datasets", "package:utils", "package:grDevices", "package:graphics", "package:stats"))
packages <- setdiff(packages, unique(matchPkg))

# Report results
if(length(packages) > 0) {
cat("Unused packages: \n");
print(packages)
} else {
cat("No unused packages found.\n")
}

关于删除 R 中未使用的库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28347362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com