【发布时间】:2021-12-06 07:07:40
【问题描述】:
我是 R 新手,在优化函数时遇到了麻烦。
我的职责是:
- 创建函数中指定的目录
- 从函数内的链接下载zip文件并解压到目录
- 如果文件是在新的子文件夹下提取的,请将提取的文件移动到主目录
- 删除子文件夹
它可以工作,但会消耗大量内存,并且需要 30 分钟才能在 2.7MB 的 zip 文件上完成如此简单的工作。
提前谢谢你!
create_dir <- function(directory) {
path <- file.path(getwd(), directory)
if (!file.exists(path)) {
dir.create(path)
}
link <-
"https://d396qusza40orc.cloudfront.net/rprog%2Fdata%2Fspecdata.zip"
temp <- tempfile()
download.file(link, temp, mode = "wb")
unzip(temp, exdir = path)
unlink(temp)
existing_loc <- list.files(path, recursive = TRUE)
for (loc in existing_loc) {
if (length(grep("/", loc))) {
file.copy(file.path(path, loc), path)
file.remove(file.path(path, loc))
}
}
dirs <- list.dirs(path)
rm_dirs <- dirs[dirs != path]
if (length(rm_dirs)) {
for (dir in rm_dirs) {
unlink(rm_dirs, recursive = TRUE)
}
}
}
create_dir("testDirectory")
【问题讨论】:
-
你分析过你的函数吗?该 zip 文件中有多少个文件?
-
zip 中的 332 个文件;总共 17.2MB。
-
感谢@Roland 对 Rprof() 的建议。这是我要探索的新领域。问题在于 OneDrive 和 AntiVirus 会同步和扫描 332 个文件的提取、移动和删除。
setwd()在本地磁盘上运行速度超级快。