Loading Data from Multiple files and saving same graph produced from each file.


I'm new to R and programming. I don't really know where to start on this. What I'd like to accomplish is having R open a file containing my seperate file names (all .csv files), and then load one file at a time, and produce the same graph from it, and saving it as a pdf but with the same title as the data file.

I've got a script running that opens one file, plots the relevant charts and saves them, but I want to scale this up so that it will load all my files one after the other, and save the graphs without me having to specify each data file name, and graph file name.

Can anyone point me in the right direction/give me an example script I can work through?

Thanks for your help,

Last edited:

Mike White

TS Contributor
The following example should help you to get started:
# datasource

# get list of files in datasource directory with names that match pattern, e.g.
# file names beginning with "data" and ending with ".csv"

source.files<-list.files(path=datasource, pattern="^data.*\\.csv$", full.names=TRUE)

for (i in 1: nfiles){
    # use same file names replacing ".csv" with ".pdf"
    pdf(file=gsub("\\.csv", ".pdf", source.files[i]))
    # code to produce chart form x data



Ambassador to the humans
For a second I was wondering what the difference between list.files and dir was. Then I looked at the help pages and the actual code and found that they're identical functions.