我是 R 的新手,并且已经构建了一系列工作循环,可以从多个子文件夹复制和重命名单个文件。
太好了!......但是这个问题是关于什么的?
好吧,我已经对 R 学习了足够多的知识,我知道大多数用户都同意应该避免循环并尽可能使用函数。这是因为函数比循环快得多。
当我将我的循环应用于我的真实数据时,它必须循环通过 +10000 个文件,因此我希望尽可能快地完成它。
我的循环可以用函数来表达吗?
或者可以以某种方式优化循环吗?
任何关于如何实现上述任何一项的示例或建议将不胜感激。
关于我的文件结构的信息:
F:/Study
1000
1001
Gait1
annotations.txt
Gait2
annotations.txt
1002
Gait1
annotations.txt
Gait2
annotations.txt
59000
59003
Gait1
annotations.txt
Gait2
annotations.txt
备注 “Gait”文件夹包含许多其他文件和目录,但我只对“annotations.txt”文件感兴趣。
我的循环:
for( a in seq(1000, 99000, by = 1000) ) {
if (!dir.exists(paste0("F:/Study/", a))) {
next()
}
for ( b in seq(1, 200, by = 1) ) {
if (!dir.exists(paste0("F:/Study/", a,"/", a+b))) {
next()
}
for ( c in seq(1, 2, by = 1)) {
if (!dir.exists(paste0("F:/Study/", a,"/", a+b, "/", "Gait", c))) {
next()
}
file.copy(from = paste0("F:/Study/", a,"/", a+b, "/", "Gait", c,"/annotations.txt"), to = "F:/Study/Annotations", overwrite = TRUE)
setwd("F:/Study/Annotations")
file.rename( from = "annotations.txt", to = paste0(a+b, "_Gait", c, "_annotations.txt") )
}
}
}
结果是我的 Annotations 文件夹中的文件名为:
1001_Gait1_annotations
1001_Gait2_annotations
1002_Gait1_annotations
1002_Gait2_annotations
59003_Gait1_annotations
59003_Gait2_annotations
tl;dr 可以用函数来表达循环吗?如何?
您可以尝试以下操作(我假设您的 /Annotations 目录已经存在)。那对你有用吗?
#get all file names (full path) with the pattern "annotations" within all folders in directory
files <- list.files("F:/Study/", full.names = TRUE, recursive = TRUE, pattern = "annotations")
#extract the desired parts for the new filename with regex
#d+ stands for 1+x digits, .* for anything and $ for the end of line
#extract only the second capturing group (the parts within parenthesis) via \\2
filenames_new <- gsub("(.*/)(\\d+/Gait\\d+.*$)", "\\2", files)
filenames_new <- gsub("/", "_", filenames_new)
#create the new filepaths
files_new <- paste0("F:/Study/Annotations/", filenames_new)
#perform copy
file.copy(from = files, to = files_new)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句