title: Using functions in R to copy the same file from multible folders and renaming the file based on folder structure
body: <p>I am new to R, and have built a working series of loops that copies and renames a single file from multible subfolders. </p>
  
  <p>Great it works!! ... but what is this question about then?</p>
  
  <p>Well, I have learned enough of R to know that most users agree that one should avoid loops and use functions instead whenever possible. This is because functions are a lot faster than loops.  </p>
  
  <p>When I apply my loop to my real data, it will have to cycle through +10000 files, and I would therefore like to make it as fast as possible. </p>
  
  <p>Can my loop be expressed by using functions instead?<br>
  Alternatively can the loop be optimized in some way?<br>
  Any examples or suggestions on how to achieve any of the above will be much appreciated.</p>
  
  <p>Info on my file-structure:</p>
  
  <pre><code>F:/Study
    1000
       1001
         Gait1
           annotations.txt
         Gait2
           annotations.txt
       1002
         Gait1
           annotations.txt
         Gait2
           annotations.txt
    59000
       59003 
         Gait1
           annotations.txt
         Gait2
           annotations.txt
  </code></pre>
  
  <p><em>nb. the "Gait" folders contain many other files and directories, but I am only interested in the "annotations.txt" files.</em></p>
  
  <p>My loop:  </p>
  
  <pre><code>for( a in seq(1000, 99000, by = 1000) ) {
    if (!dir.exists(paste0("F:/Study/", a))) {
      next()
      }
    for ( b in seq(1, 200, by = 1) ) {
        if (!dir.exists(paste0("F:/Study/", a,"/", a+b))) {
      next()
        }
      for ( c in seq(1, 2, by = 1)) {
          if (!dir.exists(paste0("F:/Study/", a,"/", a+b, "/", "Gait", c))) {
             next()
               }
        file.copy(from = paste0("F:/Study/", a,"/", a+b, "/", "Gait", c,"/annotations.txt"), to = "F:/Study/Annotations", overwrite = TRUE)
        setwd("F:/Study/Annotations")
        file.rename( from = "annotations.txt", to = paste0(a+b, "_Gait", c, "_annotations.txt") )
      }
    }
  }
  </code></pre>
  
  <p>Result is files in my Annotations folder called:  </p>
  
  <pre><code>1001_Gait1_annotations
  1001_Gait2_annotations
  1002_Gait1_annotations
  1002_Gait2_annotations
  59003_Gait1_annotations
  59003_Gait2_annotations
  </code></pre>
  
  <p>tl;dr Can the loop be expressed using functions? How?</p>