新年快乐!
你好,
我想将子文件夹中具有特定名称的文件复制到另一个文件夹(与主文件夹同名)。为了澄清我的问题,我举了一个例子。父文件夹(“Histomach”)包含 60 个子文件夹(iefirst_subfolder:“TCGA_02”、“TCGA_06”、...),每个文件夹包含 4 个子文件夹(iesecond_subfolder:“f”、“T1”、“T2”、“t1c”)也在他们每个人都有多个文件。
我想从这些文件中选择具有“_skullstrip_out.nii”等模式的特定文件,并将其复制到另一个文件夹(即“base-line”),并使用相同的第一个子文件夹名称(即“TCGA-02”、“TCGA_06”) ”,……)。
我试过这个代码。
parent_folder<-"D:/PHD/HISTOMATCH"
setwd(parent_folder)
mainfolder<-list.files(parent_folder)
first_subfolder<-list.dirs(parent_folder,recursive = FALSE)
newdir<-"D:/PHD/base_line"
dir.create(newdir)
for(i in 1:length(mainfolder)){
folder<-dir.create(paste(newdir,mainfolder[i]))}
for(i in 1:length(mainfolder)){
second_subfolder<-list.dirs(first_subfolder[i],
recursive = FALSE)
for(f in 1:length(second_subfolder)){
filesname<-list.files(second_subfolder[f])
selectefile<-grepl('-skullStrip_Output.nii.gz$',filesname)
file.copy(from =second_subfolder[f] ,to=paste(newdir,mainfolder[i]))
}
}
我该如何处理这个问题?
如果你能给我这个问题的解决方案,我将不胜感激。
先感谢您。
据我了解您的问题,我认为以下内容会让您走得更远。至少,您的所有for
循环都不是必需的。相反,您应该使用带有递归参数的现有文件操作函数。
您没有提供任何要使用的数据。我玩弄了 R 目录中的文件。我试图对“doc”文件夹中的所有 .pdf 文件做本质上相同的事情,并将它们复制到与“doc”(即工作目录)相同级别的“mytest”文件夹中。
# To make a reproducible example
setwd(R.home()) # Your working dir should be the folder "PHD" that contains "Histomach".
# Define from and to dirs, and the file pattern
from_dir <- "doc" # should be "Histomach" in your case
to_dir <- "mytest" # "base-line"
pattern <- ".pdf" # "_skullstrip_out.nii",
# Get all relevant files
the_files <- list.files(path = from_dir,
recursive = TRUE,
pattern = pattern)
# Create the "to_dir" as well as all corresponding subdirs (where files to copy were found)
sapply(file.path(to_dir, dirname(the_files)),
dir.create, recursive = TRUE, showWarnings = FALSE)
# Copy the files
file.copy(from = file.path(from_dir, the_files),
to = file.path(to_dir, the_files))
这样做你想要的吗?
要清理我在 R 文件夹中造成的混乱,请运行
file.remove(file.path(to_dir, the_files))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句