title: My R function is consuming too much memory. Can you help me optimizing it?
body: <p>I'm new to R and having trouble with optimizing a function.</p>
  <p>My function is to:</p>
  <ol>
  <li>create a directory specified in the function</li>
  <li>download the zip file from the link inside the function and extract it to the directory</li>
  <li>move extracted files to the main directory if files are extracted under a new subfolder</li>
  <li>delete the subfolder</li>
  </ol>
  <p>It works but consumes a lot of memory and takes 30mins to do such an easy job on a 2.7MB zip file.</p>
  <p>Thank you in advance!</p>
  <pre><code>create_dir &lt;- function(directory) {
    path &lt;- file.path(getwd(), directory)
    if (!file.exists(path)) {
      dir.create(path)
    }
    link &lt;-
      &quot;https://d396qusza40orc.cloudfront.net/rprog%2Fdata%2Fspecdata.zip&quot;
    temp &lt;- tempfile()
    download.file(link, temp, mode = &quot;wb&quot;)
    unzip(temp, exdir = path)
    unlink(temp)
    existing_loc &lt;- list.files(path, recursive = TRUE)
    for (loc in existing_loc) {
      if (length(grep(&quot;/&quot;, loc))) {
        file.copy(file.path(path, loc), path)
        file.remove(file.path(path, loc))
      }
    }
    dirs &lt;- list.dirs(path)
    rm_dirs &lt;- dirs[dirs != path]
    if (length(rm_dirs)) {
      for (dir in rm_dirs) {
        unlink(rm_dirs, recursive = TRUE)
      }
    }
  }
  create_dir(&quot;testDirectory&quot;)
  </code></pre>