title: R: Add column to several files in folder and save
body: <p>I am trying to apply the same function to all csv files (identical structure) in a folder - adding two new columns based on 'old' columns, adding 0.05 to each variable and then saving it under the same name in the same folder as csv. Should be easy and there are several examples here for doing that, mostly using lapply, however, I keep running into an error:</p>
  
  <pre><code>Error in `$&lt;-.data.frame`(`*tmp*`, "LAT", value = numeric(0)) : replacement has 0 rows, data has 3
  </code></pre>
  
  <p>This is my code:</p>
  
  <pre><code>my_files &lt;- list.files(path="C:/PATH", pattern=".csv", full.names=T, recursive=FALSE)
  add_col &lt;- function(my_files) {
    mpa &lt;- read.csv(my_files, header=T)
    mpa$LAT &lt;- mpa$lat_bin + 0.05
    mpa$LON &lt;- mpa$lon_bin + 0.05
    return(mpa)
    write.csv(mpa, 
              append = FALSE,
              quote = FALSE,
              sep = ",",
              row.names = FALSE,
              col.names = TRUE)
  }
  </code></pre>
  
  <p>I am unsure how best to do that for a large amounts of files.</p>
  
  <p>Here is some sample code for the files</p>
  
  <pre><code>Df1 &lt;- data.frame(lat_bin = c(50,40,70,6,8,4),lon_bin = (c(1,5,2,4,9,11)))
  Df2 &lt;- data.frame(lat_bin = c(66, 77, 82, 65, 88, 43),lon_bin = (c(2,3,4,5,11,51)))
  Df3 &lt;- data.frame(lat_bin = c(43,46,55,67,1,11),lon_bin = (c(7,6,5,9,11,15)))
  write.csv(Df1, "data_1.csv", row.names=F)
  write.csv(Df2, "data_2.csv", row.names=F)
  write.csv(Df3, "data_3.csv", row.names=F)
  </code></pre>