如何在R中的for循环中筛选列表,以便将文件从一个文件夹移动到另一个文件夹的脚本发挥作用



我正在尝试用R编写一个脚本,该脚本将把包含特定字符串的任何文件移动到用相同字符串命名的目录的子文件夹中。(子文件夹已经存在。(但是,我找不到一种方法来将我的文件列表限制为我想在任何特定实例中移动的文件(尽管可能还有另一个错误,我对R的理解不够好,无法识别(。欢迎提供任何指导。

subject <- c("a", "b", "c")
file_loc <- "C:\Users\......"
df <- data.frame (subject  = c("a", "a", "b", "c"),
filename = c("a_file1.wav", "a_file2.wav", "b_file1.wav", "c_file1.wav")
)
df_fold <- data.frame (subject = c("a", "b", "c") #this df contains a list of subjects with no repetitions - I am unsure if it is necessary or can be worked around

for (row in 1:nrow(df_fold)) {

filestocopy <- df$filename
person <- df_fold[row, "subject"]
filestocopy <- unique(grep(person, filestocopy, value=TRUE)) 

sapply(filestocopy, function(x) file.copy(from=soundfile_loc, to=paste0(soundfile_loc, person), copy.mode = TRUE, recursive=FALSE))
}

如果我理解正确的话,您确实有一个文件夹(我们称之为c:/Users/Music(,其中所有文件都以字符串(例如a(开头。并且您希望将每个文件复制到以该字符串命名的子文件夹中。

最简单的方法是首先收集所有文件名,然后收集所有子文件夹,然后检查文件名开头是否存在文件夹名称并移动它们:

folder = "C:/Users/Music/"
fnames = list.files(folder)
subdirs = fnames[!grepl(".",fnames,fixed=T)] ## Assuming that folders don't contain periods but all files do.
for(s in subdirs){
fnames.to.move = fnames[substr(fnames,1,nchar(s))==s] ## Check beginning against s
for(f in fnames.to.move){
file.copy(paste(folder,f,sep=""),paste(folder,s,"/",f,sep="")) ## Copy the files
}
}

当然,您也可以先验地定义子目录,而不是从文件名中获取子目录的名称。但是,这个简短的脚本将尝试将所有开头对应于任何子目录的文件移到此目录。

编辑:用nchar(s)替换length(s)

相关内容

最新更新