Reputation: 1
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?
Upvotes: 0
Views: 244
Reputation: 2885
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.
Upvotes: 2