Search code examples
rfor-loopnested-loopsfile-copying

for loop specific file names R


I have a list of identifiers saved as a character variable (uid_car) I have a list of files (file_list) with an identifier as the prefix to file name(eg 1000_*.file)

uid_car<-1000,1002,1004....len(170) file_list<-1000_01_.file,1001_02.file,1003_02.file,1002_01.file,1004_01.file...len(~700)

In the above example I want to loop through the file list and copy the files that have the prefix contained in uid_car. Therefore, only file 1000_01.file, 1002_01.file and 1004_01.file would be copied to a new path.

The following for loop below works until you hit an ith element not contained in uid_car.

I have tried an mapply function which is probably a bit neater but don't have as much experience writing these...any help would be appreciated.

for (i in length_of_file_list) {
  if (startsWith(file_list[i], uid_car[])) {
    file.copy(file_list[i], new_path)
  }
}

Solution

  • If you DO want to do it in a loop, this may do what you're looking for:

    uids_to_print <- c("1000", "1001", "1004")
    filenames <-c("1000_01.file","1000_02.file","1001_01.file","1001_02.file","1002_01.file","1002_02.file","1003_01.file","1004_01.file")
    
    
    # Iterate through each filename
    for (filename in filenames) {
    
        # Pull out the characters prior to the first underscore
        filename_uid <- unlist(strsplit(filename, "_"))[1]
    
        # Cheeck if it's in the list of ones to print
        if(filename_uid %in% uids_to_print) {
            # Put file operation inside this loop
    
        }
    }
    

    for example, executing

    for (filename in filenames) {
        filename_uid <- unlist(strsplit(filename, "_"))[1]
        if(filename_uid %in% uids_to_print) {
            print(paste("copy", filename, sep=" "))
        }
    }
    

    yields

    "copy 1000_01.file"
    "copy 1000_02.file"
    "copy 1001_01.file"
    "copy 1001_02.file"
    "copy 1004_01.file"