0

I have some csv files with data I want to plot in R. Right now I read each file manually, do some calculations and then plot a graph for each file. However, since I want to do exactly the same with all the data files i am trying to figure out how to do it in a for loop.

Let's say I have a folder, 'myfolder', with the files: data1.csv, data2.csv, data3.csv and I want to export the data as figure1.png, figure2.png and figure3.png.

The data files have the exact same variables just with different values.

In stata I would do it like this:

glo dir "C:/.../myfolder" 
forvalues x = 1/3 {
    import delimited using $dir/data`x'.csv, clear
    ** some calculations ** 
    graph two scatter Y X 
    graph export $dir/figure`x'.png, replace 
}

What would be the equivalent to that in R?

lmo
  • 37,904
  • 9
  • 56
  • 69
Said Hassan
  • 1
  • 1
  • 1
  • 1
    I would say these are two separate questions: answer to the first one is here: http://stackoverflow.com/questions/11433432/importing-multiple-csv-files-into-r the second then is the easier part. – s_baldur Dec 29 '16 at 20:56
  • Lots of similar posts around SO. – lmo Dec 29 '16 at 20:57

1 Answers1

2

Something like that should work:

f <- "C:/path/to/folder/"
for (i in 1:3) {
  d <- read.csv(file.path(f, paste0("data", i, ".csv")))
  # compute stuff
  png(file.path(f, paste0("figure", i, ".png")))
  plot(x, y)
  dev.off()
}

Check the documentation for file.path and plot to make sure that this is what you need.

Fr.
  • 2,865
  • 2
  • 24
  • 44
  • your third line (`d <- ...`) is missing a closing parentheses, and a call to `paste` or `paste0`. As written (but with a closing parenthesis added) it will simplify to `read.csv("C:/path/to/folder/data/1/.csv")` which is probably not what is desired here. – drammock Dec 30 '16 at 00:21