Search code examples
rfile-manipulation

Moving files to parent folder in R


I have a file structure similar to this:

D:/bu1/rp1/_archive/

D:/bu1/rp2/_archive/

D:/bu1/rp3/_archive/

D:/bu2/rp1/_archive/

D:/bu2/rp2/_archive/

D:/bu3/rp1/_archive/

D:/bu4/rp1/_archive/

D:/bu4/rp2/_archive/

and would like to move files form the '_archive' folder into their respective parent folders (e.g. from D:/bu1/rp1/_archive/ to D:/bu1/rp1).

I have each of the archive folder paths stored as a list, and think a relatively simple for loop should get the job done - I'm just unsure of how to point the files to the parent directory.


Solution

  • Sorry, this isn't tested (since I don't know what or how many files you are copying), but something like this might work

    #recreating your directory structure
    old_dirs <- list('D:/bu1/rp1/_archive/',
      'D:/bu1/rp2/_archive/',
      'D:/bu1/rp3/_archive/',
      'D:/bu2/rp1/_archive/',
      'D:/bu2/rp2/_archive/',
      'D:/bu3/rp1/_archive/',
      'D:/bu4/rp1/_archive/',
      'D:/bu4/rp2/_archive/')
    
    #splitting filepaths at underscore, which is not really generalized
    #but works for your example
    new_dirs <- strsplit(unlist(old_dirs), '_')
    new_dirs <- lapply(new_dirs, '[[', 1)
    
    #this loop probably needs some work
    for(i in old_dirs) {
      all_files <- list.files(old_dirs[[i]])
      file.copy(old_dirs[[i]], new_dirs[[i]])
    }