简体   繁体   中英

How can I filter a list within a for-loop in R so my script to move files from one folder to another will function?

I am trying to write a script in R that will move any files containing a particular string to a subfolder of that directory named with the same string. (The subfolders already exist.) However, I can't find a way to limit my list of files to the ones that I want to move in any particular instance (though it is possible there is another bug I don't understand R well enough to identify). Any guidance is appreciated.

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))

}

If I understand you correctly, you do have a folder (let's just call it c:/Users/Music ) where all files begin with a string (eg a ). And you wish to copy each file to a subfolder that is named after this string.

The easiest way to do this would be to first collect all filenames, then collect all subfolders, then check for the presence of the name of the folders in the beginning of the filenames and move them:

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,length(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
  }
}

Instead of getting the names for the subdirectories from the filenames, you could also define them a priori, of course. But This short script will try to move all files that have a beginning corresponding to any subdirectory to this directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM